Ria Choi
← Blog

Animated Hero Banner Tutorial

Part 1: Camera Movement with Three.js

Animated Hero Banner Tutorial

Intro

I am building a website for my church - Antioch International Ministry and I love every step of the way, but it’s definitely something that gives me lots of pressure.

I love my church, I love our community, and I want more people to visit through the website, and this is actually stopping me from finishing the project.

Blog image
Me and the Church Folks

But I have been stuck on this for a very long time.

I spent almost 8 months on it. I redesigned it five times. Five times, I deleted the concept, the design, and the code, and started over from zero.

Blog image
Repos being thrown away

In the end, I decided to hire a professional web designer.

But I wanted to give it a try one last time. I wanted to build an animated hero banner and start it from there.

I recently redesigned my blog UI, not a designer here, but my confidence went up a little.

Professional designers may find this funny, or even annoying. Please see it as a programmer trying to do her best without a budget.

 

This is my third time building this hero banner.

I am new to Three.js. So the first time, I practiced with simple rectangles. The second time, I built a rough version. This is the third. Writing this post makes it the fourth.

I will share every detail I learned along the way in this series.

Blog image

 

What We Will Build Today

In this animated hero banner, today we build the scene where hills slide down.

Why Three.js instead of GSAP?

I wanted a 3D feel.

I did not want elements to simply move up and down.

I wanted it to feel like a camera is filming the scene.

Today, I will share the scene where the camera films the front hills going down.

Blog image
Blog image

Prerequisite

If you are new to Three.js, do not start with Three.js.

Start with how the DOM works and what browser APIs are. I strongly recommend this.

You may feel very primitive coding with HTML, but it should be a great asset to you later on.

Here are some of the lessons on FreeCodeCamp that might be helpful for you.

Browser API Lesson
https://www.freecodecamp.org/learn/javascript-v9/lecture-working-with-the-dom-click-events-and-web-apis/what-is-an-api-and-what-are-web-apis

Media Element Lesson
https://www.freecodecamp.org/learn/javascript-v9/lecture-working-with-audio-and-video/what-is-the-htmlmediaelement-api-and-how-does-it-work

 

Then, build an audio player. You use the Audio API to play and pause sound. It is a simple way to understand the DOM and how APIs work.
https://www.freecodecamp.org/learn/javascript-v9/workshop-music-player/step-1

Blog image

 

I also recommend a project with Intersection Observer. I built one before learning GSAP. It helped me understand GSAP faster, and it gave me confidence in controlling scroll behavior.

My project used Lottie animation. The banner plays like a video as you scroll.
https://github.com/riiach/Event-Booking-Page/blob/main/script.js

Blog image

 

CSS3DRenderer

CSS3DRenderer is not a browser API: It comes from the Three.js addons, but I still want it to pin it here to give you an illustration of what browser APIs are.

Renderer Works with Good for
CSS3DRenderer HTML elements 3D cards, interactive web UI
CSS2DRenderer HTML elements Labels attached to 3D space
WebGLRenderer Canvas based 3D graphics 3D models, animation, light, shadows
WebGPURenderer GPU based 3D graphics Advanced graphics, GPU computing

 

How DOM Rendering Works

We also use createPortal from React.

What is createPortal?

Normally, a React component renders inside its parent’s DOM node.

createPortal lets you render it into a different DOM node instead.

In the React component tree, nothing changes. Only the real HTML goes somewhere else.

Why do we need it here?

CSS3DRenderer needs plain DOM elements. It moves, scales, and rotates each element with CSS transforms.

If React also controls that same element, the two will conflict. React wants to update it, and Three.js wants to move it.

So we split the jobs.

  • React owns the content, which is the hill artwork.
  • Three.js owns the container, which is the position in 3D space.

createPortal makes this split possible.

A simple example to understand how createPortal works

JSX
const element = document.createElement("div");

function MyCard() {
  return <div className="card">Hello Ria!</div>;
}

function App() {
  return (
    <div id="app">
      {createPortal(<MyCard />, element)}
    </div>
  );
}

document.body.appendChild(element);

This is what the real DOM looks like.

HTML
<body>
  <div id="app"></div>

  <div>
    <div class="card">Hello Ria!</div>
  </div>
</body>

MyCard is written inside #app in React, but it does not appear inside #app in the real DOM.

Name Role
element The real DOM container where MyCard goes
MyCard The component defined in React
createPortal() Renders MyCard inside element

In one sentence: “Keep MyCard in the React component tree, but build its real HTML inside this element.”

 

🍳 The Ingredients

Here is what we need to cook this project.

  1. A host. The box where everything renders.
  2. A Three.js setup. A scene, a camera, and a renderer.
  3. A timeline. We decide when things move and for how long.
  4. Objects. Today, these are the hills.
  5. A motion style. We want smooth movement, not robotic movement.
  6. Offset coordinates. These decide where each object moves. If only the camera moved, it would look boring. So we also give the objects their own movement.

 

Three.js Methods We Will Use

Method What it does
new THREE.Scene() Creates the space that holds all objects
new THREE.PerspectiveCamera() Creates a camera with perspective, like human eyes
new CSS3DRenderer() Creates a renderer that draws HTML elements in 3D
new CSS3DObject(element) Wraps an HTML element so it can live in the scene
scene.add() and scene.remove() Adds or removes objects from the scene
object.position.set(x, y, z) Moves an object in 3D space
camera.updateProjectionMatrix() Applies camera changes, like a new aspect ratio
THREE.MathUtils.degToRad() Converts degrees to radians
renderer.setSize(w, h) Sets the size of the render area
renderer.render(scene, camera) Draws one frame

 

Folder Structure

Blog image

I split the files by scene. Each scene has its own file or folder, so it stays small and easy to read.

The key decision is that timing lives in its own file.

Because the files are split by scene, I needed one place to control the timing of the whole animation. That place is sceneTiming.js. If I want the hills to leave faster, I change one number, and every scene stays in sync.

What about the sprite files?

Sprite files hold the artwork, like the hills and the trees. In my project, they are React components such as Hill1.jsx.

A scene only decides where a hill goes and when. It does not care how the hill looks. Keeping art and motion apart means I can redesign a hill without touching the animation.

Blog image
How the Sprite File look like

Three.js Setup

First, we set up the scene, camera, and renderer.

JavaScript
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(60, 1, 1, 10000)
const renderer = new CSS3DRenderer()

PerspectiveCamera

Value Meaning
fov How wide the field of view is
aspect The screen ratio (width divided by height)
near The closest distance that gets rendered
far The farthest distance that gets rendered

There is one more thing, camera.position. It is where the camera actually sits in 3D space.

We set aspect to 1 for now. It is just a placeholder. We fix it later in the resize function.

Blog image
fov
Blog image

Host Setup and createPortal

Next, we need a box to hold the renderer. I call it the host.

JavaScript
const hostRef = useRef(null)
const [elements] = useState(() => hills.map(() => document.createElement('div')))

We create one empty div for each hill. These are the portal targets.

Then we render them in JSX.

JSX
return (
  <div ref={hostRef} className="pointer-events-none absolute inset-0 z-5 overflow-hidden">
    {hills.map(({ Component }, index) =>
      createPortal(<Component />, elements[index], String(index))
    )}
  </div>
)

Each hill goes into its own div. Later, Three.js wraps that div with a CSS3DObject.

Why useState for the elements?

The initializer runs only once, so the div elements stay the same between re-renders. If we created them in the render body, we would get new elements every time, and Three.js would lose track of them.

Why call it host?

Most GSAP tutorials use the word “container,” so I looked for a rule. There is no strict one, but these names are commonly used like this.

Name Meaning Usually used for
hostRef Element that holds a rendering system Three.js, external library mounts
containerRef Container that wraps content General layout, Three.js
canvasRef The canvas element itself Direct access to the canvas tag
mountRef Where the renderer is mounted Three.js initialization
wrapperRef Wrapper around an element Measuring size, controlling style

I chose hostRef because this box hosts an outside system, which is Three.js.

 

The Logic

Renderer

Inside useEffect, we wrap each element and add it to the scene.

JavaScript
const objects = elements.map(element => new CSS3DObject(element))
scene.add(...objects)
renderer.domElement.className = 'absolute inset-0'
host.appendChild(renderer.domElement)

The renderer creates its own DOM element. We attach it to the host.

Shared Clock

JavaScript
const start = startedAt ?? performance.now()
let elapsed = Math.max(0, (performance.now() - start) / 1000)

Every scene uses the same start time. This keeps the hills, trees, and church in sync. If no start time is passed in, we use the current time.

Coordinate Calculation

This runs on every frame.

TypeScript
objects.forEach((object, index) => {
  const hill = hills[index]
  const movement = smoothProgress(elapsed, hill.start, hill.end - hill.start)
  const depthScale = 1 - hill.z

  object.position.set(
    width * (hill.x - hill.drift * movement) * depthScale,
    height * (-0.5 + hill.height / 2 - hill.drop * movement) * depthScale,
    distance * hill.z,
  )
  object.visible = movement < 1
})
renderer.render(scene, camera)

Let me break it down.

movement is a number from 0 to 1. At 0, the hill is at its starting position. At 1, the move is finished.

x starts at hill.x. As movement grows, we subtract drift, so the hill slides left.

y starts at -0.5 + hill.height / 2. The screen center is 0, and the bottom edge is at negative half of the height. This puts the bottom of each hill on the bottom of the screen. Then drop pulls the hill down.

z is the depth, or how far the hill is from the camera plane.

depthScale fixes a perspective problem. Far objects look smaller, and near objects look bigger. Multiplying by 1 - hill.z cancels that out, so each hill keeps the screen size we planned.

visible hides a hill once it finishes moving, so no edge is left on the screen.

Blog image

Adjustment

Resize Logic

A hero banner has to work on any screen. So we calculate everything from the host size.

TypeScript
function resize() {
  width = host.clientWidth
  height = host.clientHeight
  if (!width || !height) return
  renderer.setSize(width, height)
  camera.aspect = width / height
  camera.updateProjectionMatrix()
  distance = height / (2 * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)))
  camera.position.set(0, 0, distance)
  objects.forEach((object, index) => {
    const hill = hills[index]
    object.element.style.width = `${width * hill.width * (1 - hill.z)}px`
    object.element.style.height = `${height * hill.height * (1 - hill.z)}px`
  })
  render()
}

The distance line is the important one. It finds how far the camera must be so that 1 unit in 3D equals 1 pixel on screen at z = 0. This makes the math simple, because a width of 100 means 100px.

The size correction at the bottom uses (1 - hill.z) again, for the same reason as before.

We use ResizeObserver to run this whenever the screen changes.

JavaScript
const observer = new ResizeObserver(resize)
observer.observe(host)
resize()

We also call resize() once at the start so the first frame is correct.

Offsets

Each hill has its own settings.

YAML
const hills = [
  { Component: Hill1, x: -0.2, width: 0.9, height: 0.64, z: -0.3, start: 0,    end: 1.92, drift: 0.44, drop: 0.64 },
  { Component: Hill2, x: 0.12, width: 0.84, height: 0.60, z: 0,    start: 0.04, end: 1.96, drift: 0.45, drop: 0.65 },
  { Component: Hill3, x: 0.36, width: 0.78, height: 0.56, z: 0.28, start: 0.08, end: 2,    drift: 0.46, drop: 0.66 },
]
Key Meaning
x Starting horizontal position (ratio of screen width)
width, height Size (ratio of screen width and height)
z Depth position
start, end When the move starts and ends (in seconds)
drift How far it moves left
drop How far it moves down

The numbers are very close to each other on purpose. Big differences between the hills looked messy. Small differences looked natural. Hill1 starts first, and Hill2 and Hill3 follow 0.04 seconds apart.

Every value is a ratio, not a pixel number. That is why it works on any screen size.

Timing

All timing lives in sceneTiming.js.

JavaScript
// Shared timeline: hills descend first, and trees rise only after the hills are gone.
export const sceneTiming = {
  hillsEnd: 2,
  treeStart: 2,
  cameraDuration: 1.95,
  // Church and people rise with the tree scene, after the hill transition.
  riseStart: 2.12,
  riseDuration: 1.905,
  // Trees finish rising at 3.95s, then sway for about 1.1s before leaning.
  leanStart: 5.025,
  leanDuration: 1.05,
  exitStart: 5.85,
  exitDuration: 2.97,
  // Last tree exit and church and people zoom finish together at 9s.
  churchZoomDuration: 3.15,
  treeStagger: 0.06,
  end: 9,
}

// Smoothstep: start and finish each movement without a sudden speed change.
export function smoothProgress(elapsed, start, duration) {
  const t = Math.max(0, Math.min((elapsed - start) / duration, 1))
  return t * t * (3 - 2 * t)
}

smoothProgress is our motion style. It uses a curve called smoothstep.

Constant speed feels robotic. Smoothstep starts slowly, speeds up in the middle, and slows down at the end. It feels closer to a real camera movement.

Today we only use hillsEnd. The other values are for the next parts of the series.

The animation loop stops when the hills are done.

JavaScript
function animate(now) {
  elapsed = Math.max(0, (now - start) / 1000)
  render()
  if (elapsed < sceneTiming.hillsEnd) frame = requestAnimationFrame(animate)
}
frame = requestAnimationFrame(animate)

Once the hills are gone, there is nothing left to draw, so we stop requesting frames.

Screen Sizes

Because we use ratios and ResizeObserver, the scene adapts on its own.

  • On a wide desktop, the hills spread out wide.
  • On a narrow phone, the hills shrink with the screen.

If you want a different look for desktop and mobile, you can prepare two hills configs and pick one by screen width. I did not need that for this scene.

Cleanup

When the component unmounts, we need to clean up.

JavaScript
return () => {
  cancelAnimationFrame(frame)
  observer.disconnect()
  scene.remove(...objects)
  renderer.domElement.remove()
}

Here is what each line does.

  • cancelAnimationFrame stops the render loop.
  • observer.disconnect() stops watching the host size.
  • scene.remove() takes the objects out of the scene.
  • renderer.domElement.remove() removes the renderer’s element from the page.

Without cleanup, you can end up with duplicate loops and leftover elements. This matters in React Strict Mode, where effects run twice in development.

Voilà! There you have it!

Blog image

Full Code

Scene1GrassGoesdown.jsx

JSX
import { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import * as THREE from 'three'
import { CSS3DObject, CSS3DRenderer } from 'three/addons/renderers/CSS3DRenderer.js'
import Hill1 from '../components/Hill1.jsx'
import Hill2 from '../components/Hill2.jsx'
import Hill3 from '../components/Hill3.jsx'
import { sceneTiming, smoothProgress } from './sceneTiming.js'

// Hill layout: rectangles start around the screen middle, behind the trees.
// Subtle parallax: keep timing and travel close, with only small differences.
const hills = [
  { Component: Hill1, x: -0.2, width: 0.9, height: 0.64, z: -0.3, start: 0, end: 1.92, drift: 0.44, drop: 0.64 },
  { Component: Hill2, x: 0.12, width: 0.84, height: 0.60, z: 0, start: 0.04, end: 1.96, drift: 0.45, drop: 0.65 },
  { Component: Hill3, x: 0.36, width: 0.78, height: 0.56, z: 0.28, start: 0.08, end: 2, drift: 0.46, drop: 0.66 },
]

export default function Scene1GrassGoesdown({ startedAt }) {
  const hostRef = useRef(null)
  const [elements] = useState(() => hills.map(() => document.createElement('div')))

  useEffect(() => {
    const host = hostRef.current
    // Scene setup: use flat React hills at different Three.js Z positions.
    const scene = new THREE.Scene()
    const camera = new THREE.PerspectiveCamera(60, 1, 1, 10000)
    const renderer = new CSS3DRenderer()
    const objects = elements.map(element => new CSS3DObject(element))
    scene.add(...objects)
    renderer.domElement.className = 'absolute inset-0'
    host.appendChild(renderer.domElement)

    // Shared clock: follow the same timeline as the trees and church.
    const start = startedAt ?? performance.now()
    let frame
    let elapsed = Math.max(0, (performance.now() - start) / 1000)
    let width = 1
    let height = 1
    let distance = 1

    function render() {
      // Stagger: Hill1 starts first, then Hill2 and Hill3 at 0.04s intervals.

      objects.forEach((object, index) => {
        const hill = hills[index]
        const movement = smoothProgress(elapsed, hill.start, hill.end - hill.start)
        const depthScale = 1 - hill.z

        // First frame: bottoms align, and hill tops reach 64%, 60% and 56% up the screen.
        // 0 to 2s: descend immediately with a subtle Hill1, Hill2, Hill3 stagger.
        // Trees remain below the screen until every hill has left.
        object.position.set(
          width * (hill.x - hill.drift * movement) * depthScale,
          height * (-0.5 + hill.height / 2 - hill.drop * movement) * depthScale,
          distance * hill.z,
        )
        // Hide completed layers so no edge can remain visible after the exit.
        object.visible = movement < 1
      })
      renderer.render(scene, camera)
    }

    function resize() {
      width = host.clientWidth
      height = host.clientHeight
      if (!width || !height) return
      renderer.setSize(width, height)
      camera.aspect = width / height
      camera.updateProjectionMatrix()
      distance = height / (2 * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)))
      camera.position.set(0, 0, distance)
      objects.forEach((object, index) => {
        const hill = hills[index]
        // Size correction: keep the intended screen proportions at each depth.
        object.element.style.width = `${width * hill.width * (1 - hill.z)}px`
        object.element.style.height = `${height * hill.height * (1 - hill.z)}px`
      })
      render()
    }

    const observer = new ResizeObserver(resize)
    observer.observe(host)
    resize()

    function animate(now) {
      elapsed = Math.max(0, (now - start) / 1000)
      render()
      // All hills are gone by 2s, before the tree camera's opening movement ends.
      if (elapsed < sceneTiming.hillsEnd) frame = requestAnimationFrame(animate)
    }
    frame = requestAnimationFrame(animate)

    // Cleanup: release the frame, observer and renderer when unmounted.
    return () => {
      cancelAnimationFrame(frame)
      observer.disconnect()
      scene.remove(...objects)
      renderer.domElement.remove()
    }
  }, [elements, startedAt])

  return (
    <div ref={hostRef} className="pointer-events-none absolute inset-0 z-5 overflow-hidden" aria-label="Three hills moving down and left">
      {hills.map(({ Component }, index) => createPortal(<Component />, elements[index], String(index)))}
    </div>
  )
}

sceneTiming.js

JavaScript
// Shared timeline: hills descend first, and trees rise only after the hills are gone.
export const sceneTiming = {
  hillsEnd: 2,
  treeStart: 2,
  cameraDuration: 1.95,
  // Church and people rise with the tree scene, after the hill transition.
  riseStart: 2.12,
  riseDuration: 1.905,
  // Trees finish rising at 3.95s, then sway for about 1.1s before leaning.
  leanStart: 5.025,
  leanDuration: 1.05,
  exitStart: 5.85,
  exitDuration: 2.97,
  // Last tree exit and church and people zoom finish together at 9s.
  churchZoomDuration: 3.15,
  treeStagger: 0.06,
  end: 9,
}

// Smoothstep: start and finish each movement without a sudden speed change.
export function smoothProgress(elapsed, start, duration) {
  const t = Math.max(0, Math.min((elapsed - start) / duration, 1))
  return t * t * (3 - 2 * t)
}

What’s Next

The hills are gone. Next, the trees need to rise.

In Part 2, the camera looks up and the trees appear. We will use the same timeline file, so everything stays in sync.

Thank you for reading. See you in the next one!

Related Posts

View all