Sign up and get 15% off the four courses and Lifetime.

Scroll image reveal

A picture that opens as it scrolls into view, with a wipe, a curtain, a circle, blinds or a slow zoom, and drifts a little behind the page. Use it to pace the pictures in a case study.

Free·React and Tailwind

Try it

How to use this

  1. 01

    Make a file called scroll-mask-image.tsx in your project's components folder.

  2. 02

    Install what it needs: npm install framer-motion

  3. 03

    Paste the code in, keeping the licence note at the top.

  4. 04

    Import it where you want it and change the words, colours and sizes to yours.

The code

scroll-mask-image.tsx
/**
 * MIT License
 *
 * Copyright (c) 2024 Eduardo Calvo
 *
 * 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.
 */
"use client";

import { motion, useReducedMotion, useScroll, useSpring, useTransform } from "framer-motion";
import { type RefObject, useRef } from "react";

const cn = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");

/** Scroll offset pair, typed from `useScroll` itself. */
export type ScrollOffset = NonNullable<Parameters<typeof useScroll>[0]>["offset"];

export type ScrollMaskShape = "wipe" | "curtain" | "circle" | "blinds" | "scale";
export type ScrollMaskDirection = "left" | "right" | "up" | "down";

export interface ScrollMaskImageProps {
  src: string;
  /** Describe the image. Required. */
  alt: string;
  mask?: ScrollMaskShape;
  /** Only left/right apply to "wipe" and "blinds"; only up/down apply to "curtain". */
  direction?: ScrollMaskDirection;
  /** How far the image drifts against the scroll, in px. */
  parallax?: number;
  /** The scroll range the reveal plays over, e.g. ["start end", "end start"]. */
  offset?: ScrollOffset;
  /** A scrolling box that drives the reveal instead of the window. */
  container?: RefObject<HTMLElement>;
  /** Stay open once fully shown instead of closing again on the way back up. */
  once?: boolean;
  className?: string;
}

const DEFAULT_PARALLAX_PX = 60;
const CIRCLE_MAX_RADIUS_PERCENT = 90;
const BLIND_BAND_SIZE_PX = 40;
const SCALE_START = 1.12;
const REVEAL_SPEED_MULTIPLIER = 2.5;
const SPRING_CONFIG = { damping: 32, mass: 0.4, stiffness: 260 };
// The reveal has to land while the frame is still well in view, not as it leaves.
const DEFAULT_OFFSET: ScrollOffset = ["start 0.9", "end 0.6"];
const NO_CLIP = "inset(0% 0% 0% 0%)";

const clampUnit = (value: number) => Math.min(1, Math.max(0, value));

const buildClipPath = (mask: ScrollMaskShape, direction: ScrollMaskDirection, progress: number): string => {
  const hidden = clampUnit(1 - progress) * 100;
  if (mask === "wipe") {
    return direction === "right" ? `inset(0% 0% 0% ${hidden}%)` : `inset(0% ${hidden}% 0% 0%)`;
  }
  if (mask === "curtain") {
    return direction === "down" ? `inset(${hidden}% 0% 0% 0%)` : `inset(0% 0% ${hidden}% 0%)`;
  }
  if (mask === "circle") {
    return `circle(${clampUnit(progress) * CIRCLE_MAX_RADIUS_PERCENT}% at 50% 50%)`;
  }
  return NO_CLIP;
};

const buildBlindsMask = (direction: ScrollMaskDirection, progress: number): string => {
  const reveal = clampUnit(progress) * BLIND_BAND_SIZE_PX;
  const axis = direction === "left" || direction === "right" ? "to right" : "to bottom";
  return `repeating-linear-gradient(${axis}, #000 0px, #000 ${reveal}px, transparent ${reveal}px, transparent ${BLIND_BAND_SIZE_PX}px)`;
};

/**
 * A picture that opens as it scrolls into view: wiped in from a side, lifted like a curtain,
 * opened from the middle as a circle, drawn in as blinds or eased down from a slight zoom,
 * with a little counter-drift so it feels set behind the page.
 */
export function ScrollMaskImage({
  src,
  alt,
  mask = "wipe",
  direction = "left",
  parallax = DEFAULT_PARALLAX_PX,
  offset = DEFAULT_OFFSET,
  container,
  once = false,
  className,
}: ScrollMaskImageProps) {
  const ref = useRef<HTMLDivElement>(null);
  const shouldReduceMotion = useReducedMotion();
  const maxRevealRef = useRef(0);

  const { scrollYProgress } = useScroll({ container, offset, target: ref });
  const baseSpring = useSpring(scrollYProgress, SPRING_CONFIG);

  const revealProgress = useTransform(baseSpring, (latest) => {
    const scaled = clampUnit(latest * REVEAL_SPEED_MULTIPLIER);
    if (!once) return scaled;
    maxRevealRef.current = Math.max(maxRevealRef.current, scaled);
    return maxRevealRef.current;
  });

  // The mask sits on the frame, not the image: the image is taller than the frame so the
  // drift has room, and a clip measured on that taller box would miss the frame's edges.
  const clipPath = useTransform(revealProgress, (latest) =>
    shouldReduceMotion || mask === "blinds" || mask === "scale" ? NO_CLIP : buildClipPath(mask, direction, latest),
  );
  const maskImage = useTransform(revealProgress, (latest) =>
    shouldReduceMotion || mask !== "blinds" ? "none" : buildBlindsMask(direction, latest),
  );
  // Scales down into place from a slight zoom, never up, so no edge ever shows.
  const scale = useTransform(revealProgress, (latest) =>
    shouldReduceMotion || mask !== "scale" ? 1 : SCALE_START + (1 - SCALE_START) * clampUnit(latest),
  );
  const opacity = useTransform(revealProgress, (latest) => (shouldReduceMotion || mask !== "scale" ? 1 : clampUnit(latest)));

  const overscan = shouldReduceMotion ? 0 : Math.abs(parallax);
  const parallaxY = useTransform(baseSpring, (latest) => (shouldReduceMotion ? 0 : overscan - latest * overscan * 2));

  return (
    <motion.div
      ref={ref}
      className={cn("relative overflow-hidden rounded-2xl bg-[#e7e9ff]", className)}
      style={{ clipPath, maskImage, WebkitMaskImage: maskImage }}
    >
      <motion.img
        src={src}
        alt={alt}
        decoding="async"
        className="absolute inset-x-0 w-full object-cover"
        style={{ height: `calc(100% + ${overscan * 2}px)`, top: -overscan, opacity, scale, y: parallaxY }}
      />
    </motion.div>
  );
}
Next3D float