Codrops 원본

Building a Scroll-Driven 3D Gallery Using a Blender Camera Path with Three.js and GSAP

스크롤 · MIT

스크롤 더 보기
ORIGINAL PREVIEW
Building a Scroll-Driven 3D Gallery Using a Blender Camera Path with Three.js and GSAP 정적 미리보기

갤러리 안에서는 화면을 벗어나거나 움직임을 멈추면 예제도 닫힙니다. 다시 재생할 때는 처음부터 시작해요.

큰 화면으로 보기 새 탭

SOURCE FILES

원본 코드 읽기

6개 파일

수집한 원본 소스와 실행 안내를 함께 제공합니다.

index.html
파일 저장

<!DOCTYPE html>
<html lang="fr">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Curve Gallery</title>
  </head>
  <body>
    <div id="canvas-container"></div>

    <button id="scroll-toggle" class="scroll-toggle" type="button">Scroll</button>

    <div class="btns-container">
      <button class="path-btn active" data-path="0">Path 1</button>
      <button class="path-btn" data-path="1">Path 2</button>
      <button class="path-btn" data-path="2">Path 3</button>
      <button class="path-btn" data-path="3">Path 4</button>
      <button class="path-btn" data-path="4">Path 5</button>
    </div>

    <script type="module" src="./src/main.js"></script>
  </body>
</html>
src/main.js
파일 저장

import './style.css'
import * as THREE from 'three'
import { gsap } from 'gsap'
import { Observer } from 'gsap/Observer'

gsap.registerPlugin(Observer)

const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setPixelRatio(Math.min(devicePixelRatio, 2))
renderer.setSize(window.innerWidth, window.innerHeight)
document.getElementById('canvas-container').appendChild(renderer.domElement)

const scene = new THREE.Scene()
scene.background = new THREE.Color(0xffffff)
scene.fog = new THREE.Fog(0xffffff, 10, 40)

const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 200)


const SCALE = 16 // the curve is defined in Blender units. multiply it by 16 to obtain a consistent size within the scene.
const TEX_VARIANTS = 19 // number of images in the /img folder
const textureLoader = new THREE.TextureLoader()
const textures = loadTextureVariants(TEX_VARIANTS, textureLoader)

const TOTAL = 500 // total number of planes to create along the curve
const CAM_Z = 10 // camera offset along the Z axis
const FOCUS_DIST = 5.5 // the distance from the camera at which planes start to scale up
const MAX_SCALE = 14 // the maximum scale factor for the planes
const Z_GATE = 11 // filters out planes that are too far away in depth to avoid unnecessary calculations

const LATERAL_OFFSET_RANGE = [-1, 1]
const DEPTH_OFFSET_RANGE = [-0.75, 0.75]
const SIZE_RANGE = [0.18, 0.4]



function randomBetween(min, max) {
  return min + Math.random() * (max - min)
}

function toScaledVector3([x, y, z], scale) {
  return new THREE.Vector3(x * scale, y * scale, z * scale)
}

function loadTextureVariants(count, loader) {
  return Array.from({ length: count }, (_, i) => loader.load(`/img/${i + 1}.webp`))
}

// reconstruct a curve from the exported Blender points
function buildCurve(raw) {
  const points = raw.map(p => toScaledVector3(p, SCALE))
  return new THREE.CatmullRomCurve3(points, true, 'catmullrom', 0.5)
}

// returns position and local normal (nx, ny) at a given point on the curve
function getCurveFrame(curve, t) {
  const pos = curve.getPoint(t)
  const tangent = curve.getTangent(t)
  return { pos, nx: -tangent.y, ny: tangent.x }
}


async function init() {
  const files = ['path1', 'path2', 'path3', 'path4', 'path5']
  const allRaws = await Promise.all(
    files.map(name => fetch(`/paths/${name}.json`).then(r => r.json()))
  )

  let currentPathIndex = 0
  let curve = buildCurve(allRaws[0])

  // convert the focus distance to a t-based threshold relative to the curve length
  let focusTGate = (FOCUS_DIST * 1.5) / curve.getLength()


  function createScaleAnimator(mesh) {
    const proxy = { value: 1 }
    return gsap.quickTo(proxy, 'value', {
      duration: 0.4,
      ease: 'power3.out',
      onUpdate: () => mesh.scale.setScalar(proxy.value),
    })
  }


  const planes = []

  for (let i = 0; i < TOTAL; i++) {
    const t = i / TOTAL // distribute planes evenly along the curve

    const { pos, nx, ny } = getCurveFrame(curve, t) // get position and local normal at this point on the curve

    //random offsets to distribute the objects along the curve
    const lateralOffset = randomBetween(...LATERAL_OFFSET_RANGE) 
    const depthOffset = randomBetween(...DEPTH_OFFSET_RANGE)
    const size = randomBetween(...SIZE_RANGE)


    const mesh = new THREE.Mesh(
      new THREE.PlaneGeometry(size, size),
      new THREE.MeshBasicMaterial({
        map: textures[Math.floor(Math.random() * TEX_VARIANTS)], // assign a random texture
        side: THREE.DoubleSide,
      })
    )

    mesh.position.set(
      pos.x + nx * lateralOffset, // lateral offset in the XY plane
      pos.y + ny * lateralOffset, // lateral offset in the XY plane
      pos.z + depthOffset // depth offset
    )

    mesh.userData.t = t
    mesh.userData.lateralOffset = lateralOffset
    mesh.userData.depthOffset = depthOffset
    mesh.userData.setScale = createScaleAnimator(mesh) // attach a pre-built GSAP animator for smooth scale transitions

    planes.push(mesh)
    scene.add(mesh)

  }

  function redistributePlanes(newCurve) {
    planes.forEach((mesh) => {
      const t = mesh.userData.t
      const { pos, nx, ny } = getCurveFrame(newCurve, t)

      gsap.to(mesh.position, {
        x: pos.x + nx * mesh.userData.lateralOffset,
        y: pos.y + ny * mesh.userData.lateralOffset,
        z: pos.z + mesh.userData.depthOffset,
        duration: 1.4,
        ease: 'power3.inOut',
      })
    })
  }


  function computeFocusScale(distance, maxDistance, maxScale) {
    const f = 1 - distance / maxDistance
    return 1 + f ** 3 * (maxScale - 1)
  }


  // proxy object to allow GSAP to animate the camera's t position
  const camProxy = { t: 0 }
  const setCamT = gsap.quickTo(camProxy, 't', { duration: 1, ease: 'power3.out' })
  
  let targetT = 0

  // scroll sensitivity
  const SENSITIVITY = 0.8 / (window.innerHeight * 4)


  Observer.create({
    target: window,
    type: 'wheel,touch,pointer',
    onChange: (self) => {
      if (autoScroll) return
      targetT += self.deltaY * SENSITIVITY
      setCamT(targetT)
    },
  })


  const AUTO_SCROLL_DURATION = 10
  const AUTO_T_PER_SEC = 1 / AUTO_SCROLL_DURATION
  let autoScroll = false

  const camPos = { x: 0, y: 0, z: 0 }

  const scrollToggleBtn = document.getElementById('scroll-toggle')
  scrollToggleBtn.addEventListener('click', () => {
    autoScroll = !autoScroll
    scrollToggleBtn.classList.toggle('active', autoScroll)
    scrollToggleBtn.textContent = autoScroll ? 'Auto' : 'Scroll'
  })


  document.querySelectorAll('.path-btn').forEach((btn) => {
    btn.addEventListener('click', () => {
      const idx = parseInt(btn.dataset.path)
      if (idx === currentPathIndex) return

      currentPathIndex = idx
      document.querySelectorAll('.path-btn').forEach(b => b.classList.remove('active'))
      btn.classList.add('active')

      const newCurve = buildCurve(allRaws[idx])
      redistributePlanes(newCurve)
      curve = newCurve

      // convert the focus distance into a curve progress threshold (0 to 1)
      focusTGate = (FOCUS_DIST * 1.5) / newCurve.getLength()

      // invert and normalize t to ensure the camera moves forward when scrolling down
      const t = ((1 - camProxy.t) % 1 + 1) % 1
      const target = newCurve.getPoint(t)

      gsap.killTweensOf(camPos)
      gsap.to(camPos, {
        x: target.x,
        y: target.y,
        z: target.z + CAM_Z,
        duration: 1.4,
        ease: 'power3.inOut',
      })
    })

  })


  let lastTime = performance.now()


  function animate() {
    requestAnimationFrame(animate)

    const now = performance.now()
    const delta = (now - lastTime) / 1000
    lastTime = now

    if (autoScroll) {
      targetT += AUTO_T_PER_SEC * delta
      setCamT(targetT)
    }

    
    const t = ((1 - camProxy.t) % 1 + 1) % 1

    const pathPos = curve.getPoint(t)
    if (!gsap.isTweening(camPos)) {
      camPos.x = pathPos.x
      camPos.y = pathPos.y
      camPos.z = pathPos.z + CAM_Z
    }
    camera.position.set(camPos.x, camPos.y, camPos.z)



    for (const plane of planes) {
      const dx = camera.position.x - plane.position.x
      const dy = camera.position.y - plane.position.y
      const dz = Math.abs(camera.position.z - plane.position.z)
      const distXY = Math.sqrt(dx * dx + dy * dy)

      let dt = Math.abs(plane.userData.t - t)
      if (dt > 0.5) {
        dt = 1 - dt
      }

      const isInFocusZone = dt < focusTGate && dz < Z_GATE && distXY < FOCUS_DIST
      const targetScale = isInFocusZone ? computeFocusScale(distXY, FOCUS_DIST, MAX_SCALE) : 1

      plane.userData.setScale(targetScale)
    }

    renderer.render(scene, camera)
  }

  animate();
}


init()


window.addEventListener('resize', () => {
  const w = window.innerWidth, h = window.innerHeight
  camera.aspect = w / h
  camera.updateProjectionMatrix()
  renderer.setSize(w, h)
})
함께 쓰는 파일 4개 보기
src/style.css
파일 저장

* { 
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body { 
  width: 100vw; 
}
  

#canvas-container {
  position: fixed; 
  top: 0; 
  left: 0; 
  width: 100vw; 
  height: 100vh;
}

canvas {
  display: block;
  width: 100% !important;
  height: 100% !important;
}

.scroll-toggle {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1;
  padding: 0.65rem 1.4rem;
  border: 1px solid rgba(0, 0, 0, 0.15);
  border-radius: 999px;
  background: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(6px);
  color: #2a2a28;
  font-family: system-ui, sans-serif;
  font-size: 0.85rem;
  letter-spacing: 0.02em;
  cursor: pointer;
  transition: all 0.2s ease-in-out;
}

.scroll-toggle:hover {
  background: rgba(255, 255, 255, 0.85);
}

.scroll-toggle.active {
  background: #2a2a28;
  color: #f0ede8;
  border-color: #2a2a28;
}

.btns-container{
  position: fixed;
  display: flex;
  flex-direction: column;
  backdrop-filter: blur(6px);
  border-radius: 6px;

  bottom: 1.5rem;
  left: 1.5rem;
  gap: 8px;
  z-index: 1;
}


.path-btn {
  padding: 6px 14px;
  cursor: pointer;
  font-size: 13px;
  color: #4f4f4f;
  font-weight: 200;
  background: none;
  border: none;
}


.path-btn.active {
  color: #000000;
  font-weight: 400;
}
Original author attribution실행 안내·자료
파일 저장

Building a Scroll-Driven 3D Gallery Using a Blender Camera Path with Three.js and GSAP
Original author: Gaspard Hedde
Published by Codrops. Copyright (c) 2026 Codrops.
License: MIT, pursuant to the publisher's downloadable-demo grant.
Keep CODROPS-MIT-2026.txt and the original project notices with copies.
Third-party media exceptions and credits are recorded separately in the source inventory.
Media credits and license evidence실행 안내·자료
파일 저장

README.md
## Credits

Inspiration : https://www.cosmos.so/e/780940495
Bundled dependency licenses실행 안내·자료
파일 저장

GSAP standard license snapshot
Source: https://gsap.com/community/standard-license/
Retrieved: 2026-09-22T04:22:49.089Z
Original distribution copyright and version headers remain in the runtime code.

Standard "No Charge" GSAP License

 I. DEFINITIONS

 “GSAP License” means the terms and conditions of this GSAP Software License Agreement.

 "GSAP Products" means any Software made available at gsap.com (https://gsap.com) or any successor sites, including but not limited to the GSAP animation library and related plugins, tools, or extensions.

 "Permitted Uses" means the implementation and/or use of GSAP Products on any website, web application, or digital interface by any person or entity (which may include, for clarity, those of companies that compete with Webflow in other areas of business).

 "Prohibited Uses" means any implementation and/or use of GSAP Products in tools that allow users to build visual animations without code that encourages, induces, or materially assists in creating a solution that competes with Webflow’s visual animation building capabilities.

 "Competitive Products" means any software, tool, or service that enables users to create, edit, or manage animations through a visual interface or builder similar to Webflow (https://webflow.com).

 II. GRANT OF LICENSE

 Subject to the terms and conditions of this GSAP License, Webflow grants you a non-exclusive, worldwide license to use, reproduce, display, and implement GSAP Products solely for Permitted Uses.

 III. RESTRICTIONS

 You may not:

 Use any GSAP Products for any Prohibited Uses without prior written consent;

 Reverse engineer any GSAP Products for the purpose of creating Competitive Products;

 Remove or alter any proprietary notices or branding from GSAP Products.

 IV. OWNERSHIP AND INTELLECTUAL PROPERTY

 All intellectual property rights in GSAP Products, including but not limited to copyright, patents, trademarks, and trade secrets, remain the exclusive property of Webflow. This GSAP License does not transfer any ownership rights in GSAP Products to you.

 V. TERMINATION

 Webflow may terminate this GSAP License and revoke your access in its discretion if you fail to comply with any of these terms and conditions. Upon termination, you must cease all use of GSAP Products and destroy all copies in your possession.

 VI. MISCELLANEOUS PROVISIONS

 General: This GSAP License is incorporated into and subject to Webflow’s Terms of Service available here (https://webflow.com/legal/terms) ("Terms of Service"). In the event of any conflict or inconsistency between this GSAP License and the Terms of Service, the terms of this GSAP License shall govern in relation to your use of any GSAP Products.

 Amendments: Webflow reserves the right to update or modify this GSAP License at any time by posting the revised terms on this website, provided that any such updates or modifications shall not result in any material degradation to the security, integrity, or functionality of any GSAP Products. You understand and agree that your continued use of any GSAP Products after such revisions to this GSAP License constitutes your acceptance of this GSAP License as revised. If you do not accept the revised GSAP License, you are prohibited from using versions of the GSAP Products released after the effective date of the revised GSAP License (as well as any updates made to previous versions). Notwithstanding, you may continue using previous versions of GSAP Products under the applicable terms licensed to you prior to the effective date of the revised GSAP License (for clarity, excluding any updates made thereto).

 No Waiver: Failure of Webflow to enforce any provision of this GSAP License shall not constitute a waiver of future enforcement of that or any other provision.

 FAQ

 Is it acceptable for AI tools like ChatGPT, Cursor, Lovable, Webstudio, etc. to generate GSAP code?
 Absolutely! AI-generated code is not a "Prohibited Use".

 What if a WordPress plugin or theme or other niche tool allows users to create GSAP-driven effects through a visual interface? Is that prohibited?
 We want to encourage developers to build on top of GSAP, including visual tools that don't directly compete with Webflow's rich animation-building capabilities. If you are not sure if your product might be considered a "Prohibited Use", feel free to contact us (https://gsap.com/contact) so we can talk through it!

 Can I really use GSAP in commercial projects without paying anything?
 Yes, really! Commercial usage is covered under the standard license. All of GSAP including the plugins that were formerly "members-only" like SplitText (https://gsap.com/docs/v3/Plugins/SplitText/) and MorphSVG (https://gsap.com/docs/v3/Plugins/MorphSVGPlugin) can be used in commercial projects at no charge. Enjoy! 💚

 Effective date: April 30, 2025

 Last modified date: May 30, 2025

 Copyright (©) 2025, Webflow


three@0.184.0 — LICENSE
The MIT License

Copyright © 2010-2026 three.js authors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.