Ria Choi
← Blog

Depth Motion Background Tutorial

Let’s build depth motion BG with pixi.js

Depth Motion Background Tutorial

What Is Depth Motion?

Depth Motion makes a flat photo look three dimensional.

The kind you see on your iPhone lock screen.

Objects close to the camera move more. Objects far away move less.

The result feels like a gentle 3D parallax. It works great for hero sections and website backgrounds.

What You Need

You need two images.

  1. The original photo. This is the image people see.
  2. The depth map. This is a grayscale copy of the photo. Bright areas are near. Dark areas are far.

Both images must have the same size and aspect ratio. If they do not match, the motion will look broken.

How to Get a Depth Map for Free

You do not need Photoshop. AI can generate a depth map in seconds.

Blog image

Option 1: Depth Anything V2 on Hugging Face

  1. Search for "Depth Anything V2" on Hugging Face Spaces.
  2. Upload your photo.
  3. Download the grayscale depth map.

Option 2: Marigold Depth Estimation
It is also free on Hugging Face Spaces. It is slower but very detailed.

Option 3: Run it in your browser
Some free tools run the model on your own device. Your photo is not uploaded to a server. Search for "free AI depth map generator".

Where to find a free original photo
Try Unsplash or Pexels. Always check the license before you use an image.

Quick tips

  • Save the depth map as PNG.
  • Keep the same file size as the original.
  • If the motion looks reversed, invert the depth map.

Install Pixi.js

Bash
npm install pixi.js

Put both images in your public folder.

The Full Component

This is a Next.js client component. It also works in any React app.

JSX
"use client";

import { useEffect, useRef } from "react";

const PHOTO = "/photo.png";
const DEPTH = "/photo_depth.png";

export default function DepthBackground() {
  const hostRef = useRef(null);
  const appRef = useRef(null);
  const directionRef = useRef(0);

  useEffect(() => {
    let cancelled = false;
    let initialized = false;
    let observer;
    let filter;
    let app;

    const cleanup = () => {
      cancelled = true;
      observer?.disconnect();
      if (initialized) {
        app.destroy(true, { children: true });
        filter?.destroy();
        initialized = false;
      }
    };

    async function start() {
      const { Application, Assets, Sprite, DisplacementFilter } =
        await import("pixi.js");

      const [photoTex, depthTex] = await Promise.all([
        Assets.load(PHOTO),
        Assets.load(DEPTH),
      ]);
      if (cancelled) return;

      const host = hostRef.current;
      app = new Application();

      await app.init({
        width: host.clientWidth,
        height: host.clientHeight,
        backgroundAlpha: 0,
        resolution: Math.min(window.devicePixelRatio || 1, 2),
        autoDensity: true,
        autoStart: false,
      });
      initialized = true;

      if (cancelled) {
        cleanup();
        return;
      }

      const photo = new Sprite(photoTex);
      const depth = new Sprite(depthTex);
      photo.anchor.set(0.5);
      depth.anchor.set(0.5);
      depth.alpha = 0; // The depth sprite only drives the filter.
      app.stage.addChild(photo, depth);

      filter = new DisplacementFilter({
        sprite: depth,
        scale: { x: 0, y: 0 },
      });
      photo.filters = [filter];

      const resize = () => {
        const w = host.clientWidth;
        const h = host.clientHeight;
        app.renderer.resize(w, h);

        // Cover the container and add 8% overscan for the edges.
        const scale = Math.max(w / photoTex.width, h / photoTex.height) * 1.08;
        photo.width = photoTex.width * scale;
        photo.height = photoTex.height * scale;
        depth.width = photo.width;
        depth.height = photo.height;

        photo.position.set(w / 2, h / 2);
        depth.position.copyFrom(photo.position);
        app.render();
      };

      resize();
      observer = new ResizeObserver(resize);
      observer.observe(host);
      host.appendChild(app.canvas);

      // Spring animation
      let current = 0;
      let velocity = 0;

      app.ticker.add((ticker) => {
        const target = directionRef.current;
        const dt = Math.min(ticker.deltaMS / 1000, 1 / 30);

        velocity += ((target - current) * 180 - velocity * 17) * dt;
        current += velocity * dt;

        if (Math.abs(target - current) < 0.001 && Math.abs(velocity) < 0.01) {
          current = target;
          velocity = 0;
        }

        filter.scale.x = current * Math.min(36, app.screen.width * 0.025);

        // Stop rendering when nothing moves.
        if (current === target && velocity === 0) app.stop();
      });

      appRef.current = app;
      app.start();
    }

    start().catch((error) => {
      console.warn("Depth effect unavailable.", error);
    });

    return cleanup;
  }, []);

  function changeDirection(value) {
    directionRef.current = value;
    appRef.current?.start(); // Wake up the ticker.
  }

  return (
    <div style={{ position: "relative", width: "100%", height: "100vh" }}>
      <div ref={hostRef} style={{ position: "absolute", inset: 0 }} />
      <div style={{ position: "absolute", top: 24, right: 24, zIndex: 10 }}>
        <button onClick={() => changeDirection(1)}>Left</button>
        <button onClick={() => changeDirection(0)}>Center</button>
        <button onClick={() => changeDirection(1)}>Right</button>
      </div>
    </div>
  );
}
Note: For the Left button, pass a negative number to changeDirection. Use changeDirection(-1) for left and changeDirection(1) for right.

How It Works

1. Load both textures.
Assets.load loads the photo and the depth map at the same time.

2. Create two sprites.
The photo is what you see. The depth sprite tells Pixi how far each pixel should move.

3. Apply the DisplacementFilter.
The filter shifts each pixel based on the brightness of the depth map. Bright pixels move more.

4. Control the motion with scale.x.
A positive value pushes pixels one way. A negative value pushes them the other way.

5. Add a spring.
The spring makes the motion smooth. The image slightly overshoots, then settles.

6. Stop the ticker when idle.
When nothing moves, app.stop() saves CPU and battery.

Performance Tips

  • Load Pixi.js with a dynamic import(). It keeps your first page load small.
  • Cap the resolution at 2. Higher values slow down mobile devices.
  • Use a static image on small screens. The original code only runs the effect on desktop.
  • Respect prefers-reduced-motion. Some users do not want animation.
  • Always call destroy in the cleanup function.

Troubleshooting

The edges look cut off.
Increase the overscan. Try 1.1 instead of 1.08.

The motion looks reversed.
Invert your depth map, or flip the sign of the direction value.

The image looks stretched.
Check that the photo and depth map have the same aspect ratio.

The depth map looks blurry.
Try a higher resolution photo before you generate the depth map.

Conclusion

Depth Motion is easy to build. You need one photo, one depth map, and a DisplacementFilter.

Start with a simple version. Then add your own touches, like mouse tracking or scroll based motion.

Related Posts

View all