docs / api referencev2.31.0
Animate SVG on scroll — svg-scroll-draw API Reference
Every option, method and entry point, with the code to paste. One call draws a path as the page scrolls; the rest of the library reveals, pins, counts and scrubs on the same engine.
- Version
- 2.31.0
- Gzipped
- 11.9 KB
- Unit tests
- 1077
- Browser tests
- 359 × 3
Installation
Install via your package manager of choice, or drop in a CDN script tag — no build step required. Coming from GSAP DrawSVG? See the migration guide →
npm i svg-scroll-drawpnpm add svg-scroll-drawyarn add svg-scroll-drawbun add svg-scroll-drawCDN
<script src="https://unpkg.com/svg-scroll-draw/dist/cdn/svg-scroll-draw.global.js"></script>Exposes window.SvgScrollDraw globally. Use the <scroll-draw> custom element or call SvgScrollDraw.scrollDraw() directly.
Quick Start
Point scrollDraw() at any element containing an SVG. All path, line, rect, and circle elements inside are animated automatically.
import { scrollDraw } from 'svg-scroll-draw';
const instance = scrollDraw('#hero-svg', {
easing: 'ease-out',
speed: 1.2,
fade: true,
once: true,
onComplete: () => console.log('all paths drawn!'),
});
// Control playback later
instance.pause();
instance.resume();
instance.seek(0.5); // jump to 50%
instance.replay();
instance.destroy(); // cleanup on unmountstroke attribute and fill="none". In dev mode, a warning is logged if either condition is violated.Try it: Not sure a drawing will animate? The SVG path viewer lists each path’s length and what stops it drawing, and the SVG shape to path converter turns rects, circles and polygons into the paths they equal.
Core Options
preset'sketch' | 'reveal' | 'typewriter' | 'cinematic' | 'spring'Apply a named preset as the base configuration. User-supplied options always override the preset. See the Presets section for the full option sets.
selectorstringdefault 'path, polyline, line, polygon, rect, circle'CSS selector for elements to animate inside the container. Override to target specific paths by class or ID.
speednumberdefault 1Animation speed multiplier. Values above 1 complete the draw over a shorter scroll distance. Values below 1 slow it down.
easing'linear' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'spring' | 'bounce' | 'elastic' | `cubic-bezier(…)` | 'ease' | (t: number) => numberdefault 'linear'Easing curve applied to draw progress. Pass a custom function for full control — it receives progress from 0 to 1 and may return values outside 0–1: overshoot past 1 is how spring and elastic work. Since 2.26.0 it also takes a CSS cubic-bezier() as you would write it in a stylesheet, in every API: 'cubic-bezier(.2, .8, .2, 1)' (x1 and x2 in [0, 1]), and the keyword ease (steps() is not parsed: pass a function). The library's own names come first: ease-in, ease-out and ease-in-out are its quadratics, not the CSS keywords of the same name. Any other string (a typo like 'easeOut') warns in development, naming the value and the valid forms, and runs as the default; in 2.25 and earlier every one of these strings ran as the default without a word.
direction'forward' | 'reverse'default 'forward''forward' draws the path as you scroll in. 'reverse' starts fully drawn and erases it — useful for “write then erase” effects.
staggernumberdefault 0Delay between each path starting, as a fraction of the total scroll range. 0.1 means each path starts 10% of the range after the previous one. Each path also ends that much later, so the last one finishes after trigger.end; from 2.19.1, where the page ends before it would, the stagger is tightened just enough for the last path to finish at the bottom.
oncebooleandefault falseLock draw progress at its maximum once reached. Scrolling back up will not erase the paths. What locks is how far the scroll got, so an easing that overshoots or dips (elastic, spring, bounce, a function) still plays out and ends exactly drawn. In 2.23.2 and earlier it stayed on the overshoot, drawn past its end; fixed in 2.23.3.
Try it: Watch each named easing draw a line in the easing visualizer, or shape your own curve in the cubic-bezier generator and paste its cubic-bezier() string straight into easing (2.26.0+).
Trigger
Triggers define when the animation starts and ends relative to the scroll position. Both use an "element-anchor viewport-anchor" string format, or a percentage like "20%".
trigger.startstringdefault 'top bottom'When the animation begins. 'top bottom' means “when the top of the element hits the bottom of the viewport.” Valid anchors: top | center | bottom.
trigger.endstringdefault 'bottom top'When the animation completes. 'bottom top' means “when the bottom of the element reaches the top of the viewport.”
// Default — animates across the full scroll-through
scrollDraw('#svg', { trigger: { start: 'top bottom', end: 'bottom top' } });
// Tighter window — starts later, finishes earlier
scrollDraw('#svg', { trigger: { start: 'top 60%', end: 'bottom 40%' } });
// Percentage shorthand
scrollDraw('#svg', { trigger: { start: '20%', end: '80%' } });Try it: Set a start and end anchor in the scroll trigger visualizer and watch progress run from 0 to 1 as you scroll.
Visual Effects
fadebooleandefault falseFade the element opacity from 0→1 in sync with the draw. Combine with direction: 'reverse' to fade out while erasing.
strokeColorstring | [string, string]Static stroke color override, or interpolate between two colors as the path draws. Example: strokeColor=['#ff90e8', '#ffc900'].
strokeWidthnumber | [number, number]Static stroke width, or animate from one width to another as drawing progresses.
fillOpacitynumber | [number, number]Animate fill opacity. Pass [0, 1] to flood-fill the shape in sync with the stroke draw — no callbacks or React state needed.
clipboolean | 'left' | 'right' | 'top' | 'bottom' | 'center'Reveal the container using CSS clip-path instead of stroke animation. Works on any content — images, text, divs. true defaults to 'left'.
morphTostringTarget SVG d attribute to morph toward as the animation progresses. Source and target paths must have compatible structures — same number of commands and coordinate pairs.
// Color interpolation
scrollDraw('#svg', { strokeColor: ['#ff90e8', '#ffc900'] });
// Fill flood in sync with draw (logo reveal)
scrollDraw('#logo', { fillOpacity: [0, 1], easing: 'ease-out' });
// Clip-path reveal on an image or div
scrollDraw('#image-wrapper', { clip: 'left', speed: 0.8 });
// Path morphing
scrollDraw('#shape', { morphTo: 'M10 80 Q50 10 90 80', easing: 'spring' });Try it: Match two shapes point for point in the SVG morph generator, which writes the morphTo call; the SVG path editor lets you edit a path command by command until the two line up.
Callbacks & Waypoints
onProgress(alpha: number) => voidCalled on every animation frame with the current draw progress (0–1). Use it to drive any side effect in sync with the SVG draw.
onStart() => voidFires once when the animation begins — the first frame where progress > 0.
onComplete() => voidFires once when all paths have reached full draw progress (alpha = 1).
waypointsRecord<number, () => void>Fire callbacks at specific progress thresholds. Keys are 0–1 values. Each fires once per cycle and resets on replay().
scrollDraw('#svg', {
onStart: () => console.log('started'),
onProgress: (p) => (label.style.opacity = p),
onComplete: () => badge.classList.add('visible'),
waypoints: {
0.25: () => console.log('25% drawn'),
0.5: () => triggerConfetti(),
1.0: () => showNextSection(),
},
});Advanced Options
nativebooleandefault trueRun the draw as a native CSS scroll-driven animation when the browser supports it and the config is eligible (default trigger, named easing, optional fade, no callbacks or JS-only features). Falls back to the JS engine automatically when not eligible. Set false to always use the JS engine. The full instance API works on both paths.
autoReversebooleandefault falseAutomatically reverse the animation direction when scrolling back up. Overrides direction.
axis'x' | 'y'default 'y'Scroll axis to track. Use 'x' for horizontally-scrolling containers.
scrollContainerstring | ElementCSS selector or Element reference for a custom scroll container. Defaults to window.
delaynumberdefault 0Milliseconds to wait before the engine starts observing. Useful for staggering multiple instances on initial page load.
velocityScaleboolean | numberdefault falseScale animation speed by scroll velocity — faster scrolling draws faster. Pass a number to control sensitivity (default is 1).
repeatnumber | 'infinite'default 0Repeat the animation N times after completion. Use 'infinite' to loop forever.
repeatDelaynumberdefault 0Milliseconds to wait between animation repeats.
debugbooleandefault falseRenders a visual overlay showing the start and end trigger zones. Stripped in production — dev only.
thresholdnumberdefault 0With autoplay, the IntersectionObserver threshold (0–1) at which the run starts. A scroll-linked draw follows its trigger window and has no observer.
rootMarginstringdefault '0px'With autoplay, the IntersectionObserver rootMargin.
Paths with several subpaths
Browsers restart the dash pattern at every subpath, so one <path> whose d has several Ms draws all of them at once, each from its own start. Measured in Chromium, WebKit and Firefox: at 30% of the total length, subpaths of 360, 180 and 80 px showed 186, 180 and 80 px drawn. To draw them one after another, split them with svg-scroll-draw/subpaths (0.8 KB, an entry of its own) and let stagger order the pieces. Scroll the two below: the same path, split on the right.
<path>: every subpath at oncesplitSubpaths + stagger: 1: one after anotherimport { scrollDraw } from 'svg-scroll-draw';
import { splitSubpaths, joinSubpaths } from 'svg-scroll-draw/subpaths';
// One <path> with four subpaths: the house, its door and window (a relative
// m after z), and the sun (two arcs). Each piece draws in a window of its own.
const draw = scrollDraw(splitSubpaths('#house'), { stagger: 1 });
// To put the markup back exactly:
// draw.destroy(); joinSubpaths('#house');import { useLayoutEffect, useRef } from 'react';
import { ScrollDraw } from 'svg-scroll-draw/react';
import { splitSubpaths, joinSubpaths } from 'svg-scroll-draw/subpaths';
// A layout effect in the component that renders the <svg> runs before
// <ScrollDraw> starts, so the drawing sees the pieces.
function House() {
const svg = useRef<SVGSVGElement>(null);
useLayoutEffect(() => {
const el = svg.current;
splitSubpaths(el);
return () => { joinSubpaths(el); };
}, []);
return (
<svg ref={svg} viewBox="0 0 230 190">
<path d="M20 110 L80 60 L140 110 V170 H20 Z m40 60 v-35 h25 v35" fill="none" stroke="currentColor" />
</svg>
);
}
export function Drawing() {
return <ScrollDraw stagger={1}><House /></ScrollDraw>;
}What it does to the markup
splitSubpaths(target) takes a selector (every element it matches), an element or a list, and returns it unchanged, so it chains into any engine. Each <path> inside with more than one subpath keeps its first, so a framework that rendered it still finds its node in place; each later subpath is a copy inserted after it, with the same attributes (not id or pathLength), marked data-scroll-draw-piece. A relative m that starts a later subpath becomes an absolute M from where the piece before it ends; arcs and every other command are left to the browser’s own parser. A path with one subpath is left alone. joinSubpaths(target) removes the pieces and gives each path back its d, pathLength and style exactly.
useLayoutEffect in the component that renders the <svg>, as above. Vue: a function ref on the <svg>. Svelte, Solid, Angular and plain JavaScript: before the action, hook or scrollDraw() call. A d changed after the split does not reach the pieces: join, then split again.Handwriting: scrollWrite
svg-scroll-draw/write writes a line of text with a pen as the page scrolls: one stroke after another in writing order, the pen moving at one speed, lifting between letters and longer at a space. The text is set in a Hershey single-stroke font, so every path is the pen’s centre line, drawn once; an outline font’s letters would come out as double lines, both edges of every stroke. Scroll the two below; scrolling back unwrites them.
script: joined up, the defaultfont: 'roman': upright printimport { scrollWrite } from 'svg-scroll-draw/write';
// Writes the element's own text, 1.5 × its font size, in currentColor.
scrollWrite('#signature');
// Or say what, in which face, and keep it written.
scrollWrite('#hello', { text: 'Hello, world', font: 'roman', once: true });textstringdefault the element's textWhat to write.
font'script' | 'roman' | 'italic'default 'script'Joined-up script, upright roman, or roman slanted.
sizenumberdefault 1.5 × font sizePixels to the em. At 1.5 × the element’s font size the capitals are about as tall as the type they replace.
strokeWidthnumberdefault size / 28Line width in px.
colorstringdefault 'currentColor'Ink colour.
letterPausenumberdefault 0.3How long the pen lifts between letters, as the scroll it takes to write that many em of line.
wordPausenumberdefault 2How long it lifts at a space, in the same em.
triggerTriggerConfigdefault top 85% → top 35%The window, on the written line. The last stroke lands at its end.
oncebooleandefault falseStay written once written.
onComplete() => voidFires when the last stroke is written.
What it does to the element
The element’s content becomes an <svg> the size of the line, which scales down in a narrower parent. The <svg> is hidden from screen readers and the text stays readable in a visually hidden span, as with scrollText; destroy() puts the content back exactly. Under reduced motion the line is written at once. ASCII only: accents are dropped and curly quotes straightened. writePaths(text, { font, size }) is the layout alone, with no DOM, to render the <svg> on a server.
text, as the demo above does. The entry is 7.0 KB gzipped, most of it the two fonts; the main entry carries none of it.Instance Methods
scrollDraw() returns a ScrollDrawInstance with full playback control.
destroy()() => voidDisconnects the IntersectionObserver, cancels the rAF loop, and removes all event listeners. Always call this on component unmount.
replay()() => voidResets to initial state and replays from the beginning. Clears the once lock and waypoint history.
pause()() => voidPauses the rAF loop at the current progress. Scroll position is still tracked.
resume()() => voidResumes a paused animation from where it stopped.
seek(progress)(progress: number) => voidJump to a specific progress value (0–1) and pause. Useful for building scrubber controls.
getProgress()() => numberReturns the current draw progress as a number between 0 and 1.
const instance = scrollDraw('#svg', { easing: 'spring' });
// Scrubber slider
slider.addEventListener('input', (e) => {
instance.seek(e.target.value / 100);
});
// Pause on hover
svg.addEventListener('mouseenter', () => instance.pause());
svg.addEventListener('mouseleave', () => instance.resume());
// Cleanup
window.addEventListener('unload', () => instance.destroy());React
The React wrapper is a drop-in component that handles lifecycle automatically. All options are passed as props, and props are live: change speed or a trigger and the animation is rebuilt. A re-render with equal props — an inline object, a new arrow function — keeps the running one.
import { ScrollDraw } from 'svg-scroll-draw/react';
export function Hero() {
return (
<ScrollDraw
easing="ease-out"
speed={1.2}
fade
once
stagger={0.1}
trigger={{ start: 'top 80%', end: 'center 20%' }}
onComplete={() => console.log('done!')}
>
<svg viewBox="0 0 200 100" fill="none">
<path d="M10 50 Q100 10 190 50" stroke="black" strokeWidth="2" />
<circle cx="100" cy="50" r="30" stroke="black" strokeWidth="2" />
</svg>
</ScrollDraw>
);
}ScrollDraw component is SSR-safe: it renders your markup on the server and starts in useEffect. From v2.16.1 it carries 'use client', so a Next.js Server Component can render it directly; callbacks such as onProgress need a client component of your own. A complete project is in the Next.js guide.id, role, title, aria-* and data-* go on the rendered element; every other prop is an option. Before 2.19.0 they all became options, so a test id never reached the page.
Try it: Paste an SVG into the SVG to JSX converter for a typed React component with an optional ScrollDraw wrapper.
Vue 3
Two options: a <ScrollDraw> component, or the useScrollDraw composable for custom wrappers.
Component
<script setup>
import { ScrollDraw } from 'svg-scroll-draw/vue';
</script>
<template>
<ScrollDraw easing="ease-out" :speed="1.2" fade once>
<svg viewBox="0 0 200 100" fill="none">
<path d="M10 50 Q100 10 190 50" stroke="black" stroke-width="2" />
</svg>
</ScrollDraw>
</template>Composable
import { useScrollDraw } from 'svg-scroll-draw/vue';
// Returns a ref — attach it to your container element
const containerRef = useScrollDraw({ easing: 'spring', speed: 0.9, once: true });
// Pass a getter (or a ref) to keep options live — rebuilds when speed changes
const liveRef = useScrollDraw(() => ({ easing: 'spring', speed: speed.value }));<ScrollDraw> takes every option as a prop (it took 12), an absent boolean is left to the engine’s default, and other attributes fall through to the div.Svelte
A Svelte action — apply it to any container with use:scrollDraw. Changing its options rebuilds the animation; a new object with equal values, which Svelte passes whenever anything in the expression changes, keeps the running one.
<script>
import { scrollDraw, createScrollDraw } from 'svg-scroll-draw/svelte';
// For replay/pause control, use createScrollDraw
const { action, getInstance } = createScrollDraw({ easing: 'ease-out', speed: 1.2 });
</script>
<!-- Simple action -->
<div use:scrollDraw={{ easing: 'spring', fade: true, once: true }}>
<svg viewBox="0 0 200 100" fill="none">
<path d="M10 50 Q100 10 190 50" stroke="black" stroke-width="2" />
</svg>
</div>
<!-- With instance control -->
<div use:action>
<svg>...</svg>
</div>
<button on:click={() => getInstance()?.replay()}>Replay</button>Solid.js
A ref-setter hook — pass it to any container element via the ref prop. Pass an accessor, or a component’s props, to keep options live: the animation is rebuilt when a signal it reads changes.
import { createSignal } from 'solid-js';
import { useScrollDraw, createScrollDraw } from 'svg-scroll-draw/solid';
// Simple hook
function Hero() {
const ref = useScrollDraw({ easing: 'ease-out', fade: true, once: true });
return (
<div ref={ref}>
<svg viewBox="0 0 200 100" fill="none">
<path d="M10 50 Q100 10 190 50" stroke="black" stroke-width="2" />
</svg>
</div>
);
}
// Live options: an accessor, rebuilt when speed() changes
function LiveHero() {
const [speed, setSpeed] = createSignal(1);
const ref = useScrollDraw(() => ({ easing: 'ease-out', speed: speed() }));
return <div ref={ref}><svg>...</svg></div>;
}
// With instance control
function HeroWithReplay() {
const { ref, getInstance } = createScrollDraw({ easing: 'spring' });
return (
<>
<div ref={ref}><svg>...</svg></div>
<button onClick={() => getInstance()?.replay()}>Replay</button>
</>
);
}Angular
All v2 APIs are available as class-based Ref objects that integrate with Angular’s component lifecycle. No peer dependency on @angular/core is required in the library. Call update(options) from ngOnChanges to keep options live: it rebuilds the animation only when an option really changed.
ScrollDrawRef — SVG path drawing (v1)
import { Component, Input, ViewChild, ElementRef, AfterViewInit, OnChanges, OnDestroy } from '@angular/core';
import { ScrollDrawRef } from 'svg-scroll-draw/angular';
@Component({
selector: 'app-hero',
template: `<div #container><svg viewBox="0 0 200 100"><path d="M10 50 Q 100 10 190 50" stroke="#111" fill="none" /></svg></div>`,
})
export class HeroComponent implements AfterViewInit, OnChanges, OnDestroy {
@ViewChild('container') containerRef!: ElementRef<HTMLElement>;
@Input() speed = 1.2;
private draw = new ScrollDrawRef();
ngAfterViewInit() {
this.draw.init(this.containerRef.nativeElement, this.options());
}
// Rebuilds only when an option really changed; a no-op before init()
ngOnChanges() { this.draw.update(this.options()); }
replay() { this.draw.replay(); }
ngOnDestroy() { this.draw.destroy(); }
private options() {
return { easing: 'ease-out', speed: this.speed, fade: true, once: true };
}
}ScrollAnimateRef — animate any CSS property (v2)
import { Component, ViewChild, ElementRef, AfterViewInit, OnDestroy } from '@angular/core';
import { ScrollAnimateRef } from 'svg-scroll-draw/angular';
@Component({
selector: 'app-card',
template: `<div #el>...</div>`,
})
export class CardComponent implements AfterViewInit, OnDestroy {
@ViewChild('el') elRef!: ElementRef<HTMLElement>;
private animate = new ScrollAnimateRef();
ngAfterViewInit() {
this.animate.init(this.elRef.nativeElement, {
props: {
opacity: [0, 1],
transform: ['translateY(40px)', 'translateY(0)'],
},
easing: 'ease-out',
once: true,
});
}
ngOnDestroy() { this.animate.destroy(); }
}ScrollCounterRef — animated number (v2)
import { Component, ViewChild, ElementRef, AfterViewInit, OnDestroy } from '@angular/core';
import { ScrollCounterRef } from 'svg-scroll-draw/angular';
@Component({
selector: 'app-stats',
template: `<span #counter></span>`,
})
export class StatsComponent implements AfterViewInit, OnDestroy {
@ViewChild('counter') counterRef!: ElementRef<HTMLElement>;
private counter = new ScrollCounterRef();
ngAfterViewInit() {
this.counter.init(this.counterRef.nativeElement, {
to: 1_250_000,
format: n => '$' + Math.round(n).toLocaleString(),
once: true,
});
}
ngOnDestroy() { this.counter.destroy(); }
}ScrollTextRef — split text animation (v2)
import { Component, ViewChild, ElementRef, AfterViewInit, OnDestroy } from '@angular/core';
import { ScrollTextRef } from 'svg-scroll-draw/angular';
@Component({
selector: 'app-headline',
template: `<h2 #headline>Animate on scroll.</h2>`,
})
export class HeadlineComponent implements AfterViewInit, OnDestroy {
@ViewChild('headline') headlineRef!: ElementRef<HTMLElement>;
private text = new ScrollTextRef();
ngAfterViewInit() {
this.text.init(this.headlineRef.nativeElement, {
split: 'words',
stagger: 0.05,
from: { opacity: 0, y: 24 },
once: true,
});
}
ngOnDestroy() { this.text.destroy(); }
}update(options) and the full instance API: replay(), pause(), resume(), seek(p), getProgress(), destroy(). ScrollVideoRef follows the same pattern for <video> elements.Nuxt
svg-scroll-draw/nuxt is a Nuxt module (2.27.0+): add it to modules and every component and composable is auto-imported. Nuxt 3 and 4, no extra dependency. It also re-exports all v1 and v2 Vue composables and components, plus a plugin factory, for apps that import them by hand.
The module (recommended)
export default defineNuxtConfig({
modules: ['svg-scroll-draw/nuxt'],
// Optional. prefix: 'Ink' gives <InkScrollDraw>; either half can be left out.
svgScrollDraw: { prefix: '', components: true, composables: true },
});<script setup>
// No imports: useScrollCounter and the components are auto-imported.
const revenue = useScrollCounter({ to: 1_250_000, format: n => '$' + Math.round(n).toLocaleString() });
</script>
<template>
<ScrollDraw :once="false"><svg>…</svg></ScrollDraw>
<span ref="revenue" />
</template>v2 composables — per-component import
<script setup>
import { useScrollAnimate, useScrollText, useScrollCounter } from 'svg-scroll-draw/nuxt';
// Animate any CSS property
const card = useScrollAnimate({
props: { opacity: [0, 1], transform: ['translateY(40px)', 'translateY(0)'] },
easing: 'ease-out',
once: true,
});
// Split text and stagger animate
const headline = useScrollText({ split: 'words', stagger: 0.05, once: true });
// Animated counter
const revenue = useScrollCounter({
to: 1_250_000,
format: n => '$' + Math.round(n).toLocaleString(),
once: true,
});
</script>
<template>
<div ref="card">...</div>
<h2 ref="headline">Animate on scroll.</h2>
<span ref="revenue" />
</template>v2 components
<script setup>
import { ScrollAnimate, ScrollText, ScrollCounter } from 'svg-scroll-draw/nuxt';
</script>
<template>
<ScrollAnimate :options="{ props: { opacity: [0,1] }, easing: 'ease-out', once: true }">
<MyCard />
</ScrollAnimate>
<ScrollText :options="{ split: 'words', stagger: 0.05 }" tag="h2">
Animate on scroll.
</ScrollText>
<ScrollCounter :to="1250000" :format="n => '$' + Math.round(n).toLocaleString()" :once="true" />
</template>Global registration via Nuxt plugin
import { createScrollDrawPlugin } from 'svg-scroll-draw/nuxt';
export default defineNuxtPlugin((nuxtApp) => {
// Registers <ScrollDraw>, <ScrollAnimate>, <ScrollCounter>,
// <ScrollVideo>, <ScrollText> globally — no per-component imports.
nuxtApp.vueApp.use(createScrollDrawPlugin());
});Astro
Data-attribute APIs for all v2 animations — no framework runtime needed server-side. Options are passed as inline JSON; a single client script scans and initialises everything.
initScrollDraw — SVG path drawing (v1)
<div
data-scroll-draw
data-scroll-draw-options='{"easing":"ease-out","fade":true,"once":true}'
>
<svg viewBox="0 0 200 100" fill="none">
<path d="M10 50 Q100 10 190 50" stroke="black" stroke-width="2" />
</svg>
</div>
<script>
import { initScrollDraw } from 'svg-scroll-draw/astro';
initScrollDraw();
</script>initScrollAnimate — animate any CSS property (v2)
<div
data-scroll-animate
data-scroll-animate-options='{
"props": { "opacity": [0,1], "transform": ["translateY(40px)","translateY(0)"] },
"easing": "ease-out",
"once": true
}'
>
Fades and slides in on scroll.
</div>
<script>
import { initScrollAnimate } from 'svg-scroll-draw/astro';
initScrollAnimate();
</script>initScrollText — split text animation (v2)
<h2
data-scroll-text
data-scroll-text-options='{"split":"words","stagger":0.05,"once":true}'
>
Animate on scroll.
</h2>
<script>
import { initScrollText } from 'svg-scroll-draw/astro';
initScrollText();
</script>initAll — run every init in one call
<!-- Mix any combination of data-scroll-* attributes on the page -->
<div data-scroll-draw data-scroll-draw-options='{"easing":"ease-out"}'><svg>...</svg></div>
<div data-scroll-animate data-scroll-animate-options='{"props":{"opacity":[0,1]},"once":true}'>...</div>
<h2 data-scroll-text data-scroll-text-options='{"split":"words","stagger":0.05}'>..</h2>
<span data-scroll-counter data-scroll-counter-options='{"to":50000,"once":true}'></span>
<script>
import { initAll } from 'svg-scroll-draw/astro';
// Initialises scrollDraw + scrollAnimate + scrollText + scrollCounter in one call
const { draw, animate, text, counter } = initAll();
</script>initAll(document.querySelector('main')) — to scope initialisation to a specific subtree.From 2.19.0 each element keeps one engine per kind: editing its options attribute rebuilds it, an equal value keeps it, and running an init again — on every astro:page-load with View Transitions — keeps the engine it started. format and callbacks cannot come from JSON; use "decimals".
Web Component
A <scroll-draw> custom element that works in plain HTML, any framework, or WordPress. Bundled into the CDN script — no additional imports needed.
<script src="https://unpkg.com/svg-scroll-draw/dist/cdn/svg-scroll-draw.global.js"></script>
<scroll-draw easing="ease-out" speed="1.2" fade once>
<svg viewBox="0 0 200 100" fill="none">
<path d="M10 50 Q100 10 190 50" stroke="black" stroke-width="2" />
</svg>
</scroll-draw>String and number options map directly to HTML attributes. Boolean options like fade and once are presence-based (add the attribute to enable). From 2.19.0, changing one of these attributes later rebuilds the engine; an equal value does not.
Vanilla JS
import { scrollDraw } from 'svg-scroll-draw';
// Single element
const logo = scrollDraw('#logo', { easing: 'spring', once: true });
// Multiple elements with different configs
const chart = scrollDraw('#chart', { stagger: 0.08, speed: 0.8 });
const banner = scrollDraw('#banner', { clip: 'left', speed: 1.5 });
// Cleanup all on unload
window.addEventListener('unload', () => {
[logo, chart, banner].forEach((i) => i.destroy());
});Group API
Animate multiple SVG containers simultaneously with the same options. Each container tracks its own scroll position independently — useful for animating a grid of illustrations at once. Returns a single instance with unified control.
import { scrollDrawGroup } from 'svg-scroll-draw/group';
const group = scrollDrawGroup(
['#hero-svg', '#logo', '#diagram'],
{ easing: 'ease-out', stagger: 0.1, once: true }
);
// All instances controlled together
group.replay();
group.pause();
group.resume();
group.destroy();Sequence API
Animate multiple containers one after another — each starts only after the previous reaches 100%. Perfect for step-by-step diagram or flowchart reveals.
import { scrollDrawSequence } from 'svg-scroll-draw/group';
const seq = scrollDrawSequence(
['#step-1', '#step-2', '#step-3'],
{
easing: 'spring',
onComplete: () => console.log('all steps complete'),
}
);
seq.replay(); // restarts from step 1
seq.destroy(); // tears down all instancesuseScrollDrawProgress
A React hook that returns a reactive scroll progress value (0–1) for any element. Uses the same trigger/speed/easing semantics as scrollDraw() — use it to drive any animation alongside or independent of an SVG draw.
import { useRef } from 'react';
import { useScrollDrawProgress } from 'svg-scroll-draw/react';
export function ParallaxSection() {
const ref = useRef<HTMLDivElement>(null);
const progress = useScrollDrawProgress(ref, {
speed: 1.2,
easing: 'ease-out',
trigger: { start: 'top 80%', end: 'center 20%' },
});
return (
<div ref={ref}>
<div
style={{
transform: `translateY(${(1 - progress) * 40}px)`,
opacity: progress,
}}
>
<h2>Fades and slides in as you scroll</h2>
</div>
</div>
);
}Options
speednumberdefault 1Same speed multiplier as scrollDraw().
easingEasing (a name, a CSS cubic-bezier() string, or (t: number) => number)default 'linear'Same easing curves as scrollDraw().
triggerTriggerConfigSame trigger syntax. Default: start 'top bottom', end 'bottom top'.
axis'x' | 'y'default 'y'Scroll axis.
scrollContainerstring | ElementCustom scroll container.
oncebooleandefault falseLock at max progress once reached — never decreases on scroll back.
Native CSS rendering
For the common case, svg-scroll-draw hands the animation to the browser’s native animation-timeline: view(). The browser drives the draw from the scroll position, with zero per-frame JavaScript and no scroll or resize listeners. (The stroke still repaints on the main thread — browsers don't composite stroke-dashoffset — but no script runs per frame.) It falls back to the JS engine automatically when the browser lacks support, or when the config uses a feature CSS can't express declaratively.
Eligible for native CSS
Default trigger, optional fade, forward or reverse direction, and one of four named easings: linear, ease-in, ease-out, ease-in-out. Those four are emitted as CSS timing functions that reproduce this library's own curves — not the CSS keywords of the same name, which are different curves and differ by up to 0.069. Since 2.26.0 a CSS cubic-bezier() string you pass is eligible too, and goes to CSS as written, so both engines run the same curve. Any other easing (spring, bounce, elastic, or a function) declines the fast path and stays on the JS engine rather than being approximated.
Falls back to JS engine automatically
onProgress / onComplete / waypoints, stagger, morphTo, velocityScale, autoReverse, once, repeat, custom trigger, custom scroll container, speed ≠ 1, spring easing, animated color/width/fill, autoplay and debug in a development build (a production build draws no trigger lines, so since 2.23.4 debug left on there keeps the fast path). In 2.23.2 and earlier those last two did not count: a plain { autoplay: true } followed the scroll instead of playing over its duration, and { debug: true } drew no trigger lines, in every browser with view timelines. Fixed in 2.23.3.
Jumping straight past a drawing
The one place the two paths differ. Jump past a drawing without ever showing it — a deep link, a restored scroll position, scrollTo(0, document.body.scrollHeight) — and the native path holds its end state, because the animation fills both ways, while the JS engine, which only runs while the container is on screen, leaves it undrawn. You can’t see either while it is off screen, and the JS engine catches up on the first frame the drawing scrolls back into view. What you can see is the reading: off screen, getProgress() and the path’s computed stroke-dashoffset report the end on the native path and the start on the JS engine. The browser suite pins this behaviour in e2e/parity.spec.ts, so a change to it is a decision rather than an accident.
// Uses animation-timeline: view() on supporting browsers
scrollDraw('#svg', { easing: 'ease-out', fade: true });
// Force JS engine regardless
scrollDraw('#svg', { native: false, easing: 'spring' });pause, resume, seek, replay, destroy — works on both paths.Try it: The CSS scroll-driven animation generator writes animation-timeline CSS for seven effects, and the SVG line drawing generator turns any SVG into a file that draws itself with CSS alone.
createSpring
Returns a custom spring easing function. The built-in 'spring' easing is hardcoded — createSpring lets you tune it.
tensionnumberdefault 2.5Oscillation frequency. Higher = more bouncy, faster oscillation.
frictionnumberdefault 2.2Damping strength. Higher = less bouncy, settles faster.
import { scrollDraw, createSpring } from 'svg-scroll-draw';
// Gentle bounce — close to the built-in 'spring'
scrollDraw('#svg', { easing: createSpring() });
// Tight, snappy spring
scrollDraw('#svg', { easing: createSpring({ tension: 4, friction: 3 }) });
// Slow, wobbly spring
scrollDraw('#svg', { easing: createSpring({ tension: 1.5, friction: 1.2 }) });createSpring() with no arguments produces the same curve as easing: 'spring'. Use it when you need to parameterize the bounce.createBounce
Returns a bounce-out easing. The animation rises to 1 via ease-out, then makes bounces − 1 dips below 1 that settle — like a ball landing. The rise is the first of the bounces segments. Output stays within [0, 1].
bouncesnumberdefault 3Segments, the first rise included, so bounces − 1 dips follow it: the default 3 is a rise and two dips. Higher = more dips before settling.
decaynumberdefault 0.5Amplitude reduction per bounce (0–1). Lower = faster decay, shallower bounces.
import { scrollDraw, createBounce } from 'svg-scroll-draw';
// Named string — default params (bounces: 3, a rise and two dips; decay 0.5)
scrollDraw('#svg', { easing: 'bounce' });
// Four quick dips
scrollDraw('#svg', { easing: createBounce({ bounces: 5, decay: 0.35 }) });
// One slow, deep dip
scrollDraw('#svg', { easing: createBounce({ bounces: 2, decay: 0.7 }) });createElastic
Returns an elastic-out easing. The animation overshoots past 1 and oscillates back before settling — like a rubber band snapping into place. Can produce values slightly outside [0, 1]; for SVG paths this appears as a brief over-draw.
amplitudenumberdefault 1Overshoot magnitude (≥1). Default overshoots to ~1.25; try 1.5 for a dramatic snap.
periodnumberdefault 0.4Oscillation period in scroll-time. Smaller = faster oscillations; larger = slow wobble.
import { scrollDraw, createElastic } from 'svg-scroll-draw';
// Named string — default params (amplitude 1, period 0.4)
scrollDraw('#svg', { easing: 'elastic' });
// Big snap, fast oscillation
scrollDraw('#svg', { easing: createElastic({ amplitude: 1.5, period: 0.3 }) });
// Subtle, slow wobble
scrollDraw('#svg', { easing: createElastic({ amplitude: 1.1, period: 0.6 }) });bounce and elastic with live parameter sliders.scrollDrawTimeline
Animate multiple path groups with independent start/end windows within a single scroll range. Unlike stagger (which offsets by time), each track defines its own from/to slice of the 0–1 progress range — and they can overlap freely.
import { scrollDrawTimeline } from 'svg-scroll-draw/timeline';
const instance = scrollDrawTimeline('#diagram', {
trigger: { start: 'top 80%', end: 'bottom 20%' },
tracks: [
// Axes draw first
{ selector: '.axis', from: 0, to: 0.3, easing: 'ease-out' },
// Bars stagger, each with its own window
{ selector: '.bar-q1', from: 0.1, to: 0.45, easing: 'ease-out' },
{ selector: '.bar-q2', from: 0.28, to: 0.58, easing: 'ease-out' },
{ selector: '.bar-q3', from: 0.45, to: 0.75, easing: 'ease-out' },
{ selector: '.bar-q4', from: 0.6, to: 0.88, easing: 'ease-out' },
// Trend line traces last
{ selector: '.trend', from: 0.75, to: 1.0, easing: 'spring' },
],
onComplete: () => console.log('all tracks done'),
});
instance.seek(0.5); // jump to 50% of total range
instance.destroy();Track options
selectorstringCSS selector for SVG elements to animate on this track — scoped to the container.
fromnumberProgress value (0–1) within the overall range where this track starts drawing.
tonumberProgress value (0–1) within the overall range where this track finishes drawing.
easingEasingName | CSS cubic-bezier() string | functiondefault 'linear'Easing applied to this track’s local progress independently of other tracks.
fadebooleandefault falseFade opacity in sync with this track’s draw progress.
Timeline-level options
triggerTriggerConfigSame trigger syntax as scrollDraw().
speednumberdefault 1Overall speed multiplier applied to the full range.
oncebooleandefault falseLock at max progress once reached.
axis'x' | 'y'default 'y'Scroll axis.
onComplete() => voidFires when the overall progress reaches 1.
repeatnumber | 'infinite'default 0Replay N times after completing (with once: true). After completion + repeatDelay ms, paths reset and animate again on next scroll-into-view.
repeatDelaynumberdefault 0Milliseconds to wait before each repeat or loop iteration.
loopboolean | numberdefault falseAfter the scroll-driven animation completes, automatically replay as a time-driven loop — no further scroll needed. true = loop forever, number = loop N additional times. Each iteration plays over loopDuration ms.
loopDurationnumberdefault 1500Duration of each time-driven loop iteration in milliseconds.
debugbooleandefault falseInject a fixed HUD panel into document.body showing each track’s scroll window as a coloured progress bar with live fill and global progress. Removed on destroy(). Useful for tuning from/to values.
labelstringLabel shown in the debug panel header. Defaults to the target selector.
Presets
Named option bags for common scroll-draw patterns. Pass preset as a shorthand — user options always override preset values.
import { scrollDraw } from 'svg-scroll-draw';
// One-liner for common patterns
scrollDraw('#logo', { preset: 'reveal' });
scrollDraw('#diagram', { preset: 'sketch' });
scrollDraw('#text', { preset: 'typewriter' });
scrollDraw('#hero', { preset: 'cinematic' });
scrollDraw('#icon', { preset: 'spring' });
// Override any preset value
scrollDraw('#logo', { preset: 'reveal', easing: 'spring' });
// Inspect presets directly
import { PRESETS } from 'svg-scroll-draw';
console.log(PRESETS.reveal);
// { easing: 'ease-out', fade: true, speed: 1.2, once: true }Available presets
'sketch'presetStaggered ease-in draw — paths trace in one by one. Pencil-drawing feel. Sets: easing: 'ease-in', stagger: 0.1, speed: 0.9.
'reveal'presetClean viewport reveal — fades and draws in once. Best for logos and hero graphics. Sets: easing: 'ease-out', fade: true, speed: 1.2, once: true.
'typewriter'presetFast mechanical draw — paths appear quickly one after another. Sets: easing: 'linear', stagger: 0.05, speed: 1.5.
'cinematic'presetSlow dramatic entrance — long ease-in-out with a gentle fade. Sets: easing: 'ease-in-out', fade: true, speed: 0.75.
'spring'presetBouncy physics feel — spring easing gives a natural overshoot-and-settle. Sets: easing: 'spring', speed: 1.1.
CLI — npx svg-scroll-draw init
An interactive scaffolder that generates a starter file for your framework — no manual copy-paste from the docs needed.
npx svg-scroll-draw initThe CLI asks for your framework, preset, easing, and SVG selector, then writes a ready-to-use file:
Output by framework
reactWrites ScrollDraw.tsx — a client component with <ScrollDraw> and a sample SVG.
vueWrites ScrollDraw.vue — a SFC with useScrollDraw composable wired up.
svelteWrites ScrollDraw.svelte — uses the use:scrollDraw action.
solidWrites ScrollDraw.tsx — uses createScrollDraw.
vanillaWrites scroll-draw.js — a plain scrollDraw() call.
CSS Custom Property
Every scrollDraw() instance automatically sets --scroll-draw-progress on the container element on every animation frame. Use it to drive CSS animations without any JS callbacks.
/* Drive any CSS property directly from scroll progress */
.hero-text {
opacity: var(--scroll-draw-progress);
transform: translateY(calc((1 - var(--scroll-draw-progress)) * 24px));
}
.highlight {
background-size: calc(var(--scroll-draw-progress) * 100%) 100%;
}
.counter {
/* Combine with @property for smooth transitions */
color: oklch(from var(--scroll-draw-progress) 60% 0.2 250);
}import { scrollDraw } from 'svg-scroll-draw';
// No onProgress callback needed —
// --scroll-draw-progress is set automatically
scrollDraw('#hero-svg', { easing: 'ease-out', once: true });
// The CSS does the rest:onProgress and getProgress() report the same value; with stagger, onComplete waits for the last path.Vue 3 — v2 composables & components
All v2 APIs now have first-class Vue 3 support. Each API ships as a composable (returns a ref to bind to any element) and a convenience component wrapper. Imports from svg-scroll-draw/vue.
useScrollAnimate + <ScrollAnimate>
<script setup>
import { useScrollAnimate, ScrollAnimate } from 'svg-scroll-draw/vue';
const el = useScrollAnimate({
props: { opacity: [0, 1], transform: ['translateY(40px)', 'translateY(0)'] },
easing: 'ease-out',
once: true,
});
</script>
<template>
<div ref="el">Animates on scroll.</div>
<!-- Or use the component wrapper: -->
<ScrollAnimate :options="{ props: { opacity: [0, 1] }, easing: 'ease-out', once: true }">
<div>Animates on scroll.</div>
</ScrollAnimate>
</template>useScrollCounter + <ScrollCounter>
<script setup>
import { useScrollCounter, ScrollCounter } from 'svg-scroll-draw/vue';
const el = useScrollCounter({
to: 1_250_000,
format: n => '$' + Math.round(n).toLocaleString(),
easing: 'ease-out',
once: true,
});
</script>
<template>
<span ref="el" />
<!-- Or use the component: -->
<ScrollCounter
:to="1250000"
:format="n => '$' + Math.round(n).toLocaleString()"
easing="ease-out"
:once="true"
/>
</template>useScrollVideo + <ScrollVideo>
<script setup>
import { useScrollVideo, ScrollVideo } from 'svg-scroll-draw/vue';
const vid = useScrollVideo({
trigger: { start: 'top top', end: 'bottom top' },
});
</script>
<template>
<video ref="vid" src="/hero.mp4" muted playsinline preload="auto" />
<!-- Or use the component: -->
<ScrollVideo
src="/hero.mp4"
:options="{ trigger: { start: 'top top', end: 'bottom top' } }"
/>
</template>useScrollText + <ScrollText>
<script setup>
import { useScrollText, ScrollText } from 'svg-scroll-draw/vue';
const el = useScrollText({
split: 'words',
stagger: 0.05,
from: { opacity: 0, y: 24 },
once: true,
});
</script>
<template>
<h2 ref="el">Animate on scroll.</h2>
<!-- Or use the component (tag defaults to "p"): -->
<ScrollText :options="{ split: 'words', stagger: 0.05 }" tag="h2">
Animate on scroll.
</ScrollText>
</template>Svelte — v2 actions & helpers
All v2 APIs are available as Svelte use: actions. Each has a matching create* helper that exposes the live instance for imperative control. Imports from svg-scroll-draw/svelte.
scrollAnimate action
<script>
import { scrollAnimate } from 'svg-scroll-draw/svelte';
const opts = {
props: { opacity: [0, 1], transform: ['translateY(40px)', 'translateY(0)'] },
easing: 'ease-out',
once: true,
};
</script>
<div use:scrollAnimate={opts}>Animates on scroll.</div>scrollCounterAction action
<script>
import { scrollCounterAction } from 'svg-scroll-draw/svelte';
</script>
<span use:scrollCounterAction={{ to: 1250000, format: n => '$' + Math.round(n).toLocaleString(), once: true }} />scrollTextAction action
<script>
import { scrollTextAction } from 'svg-scroll-draw/svelte';
</script>
<h2 use:scrollTextAction={{ split: 'words', stagger: 0.05, once: true }}>
Animate on scroll.
</h2>createScrollAnimate — imperative control
<script>
import { createScrollAnimate } from 'svg-scroll-draw/svelte';
const { action, getInstance } = createScrollAnimate({
props: { opacity: [0, 1] },
easing: 'ease-out',
once: true,
});
</script>
<div use:action>...</div>
<button on:click={() => getInstance()?.replay()}>Replay</button>create* pattern is available for all v2 actions: createScrollCounter, createScrollVideo, createScrollText.Solid.js — v2 hooks
All v2 APIs are available as SolidJS hooks. Each use* hook returns a ref setter. The matching create* variant returns { ref, getInstance } for imperative control. Imports from svg-scroll-draw/solid.
useScrollAnimate
import { useScrollAnimate } from 'svg-scroll-draw/solid';
function Hero() {
const ref = useScrollAnimate({
props: { opacity: [0, 1], transform: ['translateY(40px)', 'translateY(0)'] },
easing: 'ease-out',
once: true,
});
return <div ref={ref}>Animates on scroll.</div>;
}useScrollCounter
import { useScrollCounter } from 'svg-scroll-draw/solid';
function Revenue() {
const ref = useScrollCounter({
to: 1_250_000,
format: n => '$' + Math.round(n).toLocaleString(),
easing: 'ease-out',
once: true,
});
return <span ref={ref} />;
}useScrollText
import { useScrollText } from 'svg-scroll-draw/solid';
function Headline() {
const ref = useScrollText({
split: 'words',
stagger: 0.05,
from: { opacity: 0, y: 24 },
once: true,
});
return <h2 ref={ref}>Animate on scroll.</h2>;
}createScrollAnimate — imperative control
import { createScrollAnimate } from 'svg-scroll-draw/solid';
function Hero() {
const { ref, getInstance } = createScrollAnimate({
props: { opacity: [0, 1] },
easing: 'ease-out',
once: true,
});
return (
<>
<div ref={ref}>...</div>
<button onClick={() => getInstance()?.replay()}>Replay</button>
</>
);
}create* pattern is available for all v2 hooks: createScrollCounter, createScrollVideo, createScrollText.refresh()
Re-measure after a layout change: path lengths, and the scroll trigger window. The engine already re-measures on resize, on orientationchange, and through a ResizeObserver on the document element — but none of those fire for a change that leaves the document height alone, such as a tab switching, a sibling collapsing, or a font swapping inside a fixed-height box.
const draw = scrollDraw('#diagram');
// After swapping the SVG, or revealing a hidden tab panel:
draw.refresh();
// Available on the timeline and the group APIs too
const group = scrollDrawGroup(['#a', '#b']);
group.refresh(); // reaches every memberscrollDraw, scrollDrawTimeline, the group and sequence APIs, scrollPin and scrollHorizontal. It is optional on the shared instance type, because a few instances are fan-outs or SSR stubs — use instance.refresh?.() if you hold one of unknown origin.Timeline & reduced motion
scrollDrawTimeline now takes respectReducedMotion (default true), and it applies to the time-driven loop only.
The two halves of the API deserve different answers. Scroll scrubbing advances 1:1 with the user's own input — direct manipulation, not motion played at them — so it keeps working. The loop replays the whole timeline off a timer with no scroll input at all, which is autonomous motion, so with reduced motion requested it simply does not start. The preference is tracked live, so toggling the OS setting takes effect without a reload.
scrollDrawTimeline('#diagram', {
tracks: [{ selector: '.line', from: 0, to: 1 }],
loop: true,
loopDuration: 1500,
// Default. Set false to loop regardless of the preference.
respectReducedMotion: true,
});CDN development build
A second CDN bundle that reports mistakes. The production build's warnings are compiled out, and before 2.10.0 there was no other build — the warnings were gated on process.env.NODE_ENV, and process does not exist in a browser without a bundler, so a <script src> user could never see one.
<!-- While developing: unminified, and it tells you what is wrong -->
<script src="https://unpkg.com/svg-scroll-draw/dist/cdn/svg-scroll-draw.dev.global.js"></script>
<!-- In production: minified, silent -->
<script src="https://unpkg.com/svg-scroll-draw/dist/cdn/svg-scroll-draw.global.js"></script>morphTo whose commands do not correspond — and a trigger window with zero length, which is an element that looks configured and will never move.scrollProgress
Expose scroll progress as CSS custom properties on a target element. Drive opacity, transforms, colors, gradients — anything CSS can express — directly from calc() expressions with zero per-frame JS beyond the variable write. Two properties are set: raw (linear) and eased.
import { scrollProgress } from 'svg-scroll-draw/progress';
// Set --scroll-progress (raw) and --scroll-progress-eased on the element
scrollProgress('#hero', { easing: 'ease-in-out' });
// Custom variable names
scrollProgress('#section', {
variable: '--my-progress',
easedVariable: '--my-progress-eased',
trigger: { start: 'top 80%', end: 'bottom 20%' },
});
// Use in CSS
// #hero {
// opacity: calc(var(--scroll-progress-eased));
// transform: translateY(
// calc((1 - var(--scroll-progress-eased)) * 40px)
// );
// }| Option | Type | Default | Description |
|---|---|---|---|
| variable | string | "--scroll-progress" | Raw (linear) 0–1 progress property. |
| easedVariable | string | null | "--scroll-progress-eased" | Eased 0–1 progress property. Set to null to skip. |
| trigger | TriggerConfig | top bottom / bottom top | Scroll window for 0→1 mapping. |
| easing | EasingName | fn | "linear" | Easing applied to the eased variable. |
| speed | number | 1 | Animation speed scale. |
| axis | "x" | "y" | "y" | Scroll axis. |
| scrollContainer | string | Element | — | Custom scroll container. |
| onProgress | (raw, eased) => void | — | Callback fired every frame with both values. |
Try it: Build a reading bar on any edge, or a ring, in the scroll progress bar generator.
scrollHorizontal
Drive horizontal translateX from vertical scroll — the Apple / Stripe “scroll sideways” pattern. You handle the sticky CSS;scrollHorizontal drives the transform.
import { scrollHorizontal } from 'svg-scroll-draw/horizontal';
// Minimal CSS:
// .outer { height: 400vh; }
// .sticky { position: sticky; top: 0; height: 100vh; overflow: clip; }
// .track { display: flex; width: max-content; }
// No distance: the track's width minus the sticky stage's, measured
// again whenever the window, the page, the track or the runway resizes.
const inst = scrollHorizontal('.track', {
onProgress: (p) => dots.setActive(Math.round(p * 3)),
});
// React
useEffect(() => {
const inst = scrollHorizontal(trackRef.current);
return () => inst.destroy();
}, []);
inst.refresh(); // re-measure now, after a change nothing resized
inst.destroy(); // cleanup| Option | Type | Default | Description |
|---|---|---|---|
| distance | number | track − stage | Total horizontal travel in px. Defaults to the track’s width minus the content box of its sticky stage (or, without one, the scroll container’s or the viewport’s width, scrollbar left out), and is measured again when the layout changes (2.18.1). A number you pass is used as given. |
| trigger | TriggerConfig | { start: "top top", end: "bottom bottom" } | Scroll window the travel is mapped across. |
| easing | EasingName | fn | "linear" | Easing for the movement. Linear gives the scrub feel. |
| triggerElement | string | Element | Sticky parent | Element whose height defines the scroll window. Defaults to the container of the track’s nearest position:sticky ancestor — the element that actually holds the scroll room. A sticky-pinned track is only one viewport tall, so measuring against it would give a zero-length window and no movement. |
| respectReducedMotion | boolean | false | Unlike other APIs here, defaults to false. The transform is scroll-linked scrubbing — it advances only as the user scrolls — and holding a final state instead would leave every panel but one unreachable inside the sticky container. Set true if you have a non-transform fallback; the strip then also holds still if the reader turns reduced motion on mid-visit. |
| scrollContainer | string | Element | window | Custom scroll container. |
| onProgress | (p: number) => void | — | Fires every frame with 0–1 progress through the window. |
Try it: Set the panels, gap and scroll length in the horizontal scroll generator and copy the sticky CSS with the JS.
scrollReveal
Reveal elements as they scroll into view. One-line replacement for AOS and ScrollReveal.js — no data attributes, fully typed, 7 named presets, stagger, and custom easing.
import { scrollReveal } from 'svg-scroll-draw/reveal';
// Default: fade up
scrollReveal('.card');
// Named preset
scrollReveal('.feature', { preset: 'scale' });
// Custom from state
scrollReveal('.item', {
from: { opacity: 0, y: 40, scale: 0.95 },
stagger: 0.1,
easing: 'ease-out',
once: true,
});
// Presets: 'fadeUp' | 'fadeDown' | 'fadeLeft' | 'fadeRight' | 'scale' | 'flip' | 'flipX'
// Cleanup
const instance = scrollReveal('.card', { preset: 'fadeUp' });
instance.destroy();| Option | Type | Default | Description |
|---|---|---|---|
| preset | ScrollRevealPreset | "fadeUp" | Named start state. fadeUp | fadeDown | fadeLeft | fadeRight | scale | flip | flipX |
| from | ScrollRevealFrom | — | Custom start state: { opacity, x, y, scale, rotate, rotateX, rotateY }. Merges with preset. |
| stagger | number | 0.15 | How far behind its neighbour each element in the same row starts, as a fraction of the reveal window (0–1). Rows are read from the layout, so a grid cascades within each row; applies on top of a custom trigger too. |
| easing | EasingName | fn | "ease-out" | Animation easing. |
| once | boolean | true | Freeze at max progress — don't reverse on scroll back. |
| trigger | TriggerConfig | "top 88%" → "top 53%" | Override the reveal window. The stagger offset is added on top of it, per element. |
| onEnter | () => void | — | Fires when the first element enters its trigger zone. |
| onLeave | () => void | — | Fires when the last element leaves its trigger zone. |
Try it: Pick a preset, stagger and trigger in the scroll reveal generator and copy one scrollReveal call.
velocityScale
Scale animation speed by scroll velocity — the faster the user scrolls, the faster the animation progresses. Available on scrollAnimate (and already on scrollDraw). Pass true for default sensitivity or a number to tune it.
import { scrollAnimate } from 'svg-scroll-draw';
// Default sensitivity (1) — moderate speed-up on fast scroll
scrollAnimate('#hero', {
props: { opacity: [0, 1], transform: ['translateY(32px)', 'translateY(0)'] },
velocityScale: true,
});
// High sensitivity (3) — very responsive to scroll speed
scrollAnimate('#kinetic-bg', {
props: { transform: ['translateY(0px)', 'translateY(-200px)'] },
velocityScale: 3,
easing: 'linear',
});
// velocityScale is available on scrollDraw too:
scrollDraw('#logo', {
easing: 'ease-out',
velocityScale: 1.5,
});velocityScale forces the JS engine — the native CSS fast path is skipped because velocity requires per-frame measurement.scrollPin
Pin any element at a viewport position while the page scrolls past it. Wrapper-based — inserts a spacer to prevent layout shift. Full lifecycle callbacks mirror GSAP ScrollTrigger's pin: true.
import { scrollPin } from 'svg-scroll-draw/pin';
// Pin at top of viewport for one viewport-height of scroll
const pin = scrollPin('#panel', {
pinDistance: '100vh', // one screen; holds still while a phone's address bar slides
onEnter: () => panel.classList.add('active'),
onLeave: () => panel.classList.remove('active'),
onEnterBack: () => panel.classList.add('active'),
onLeaveBack: () => panel.classList.remove('active'),
onProgress: (p) => console.log('progress', p), // 0–1 through pin zone
});
// Apple-style: pin image, scroll text past it
scrollPin('#product-image', {
top: 80, // pin 80px from viewport top (below a fixed nav)
pinDistance: 800, // hold for 800px of scroll
});
// Recalculate after layout change (accordion, dynamic content)
pin.refresh();
// Remove on unmount / route change
pin.destroy();| Option | Type | Default | Description |
|---|---|---|---|
| pinDistance | number | '150vh' | window.innerHeight | Scroll to stay pinned. A number is pixels and stays fixed; '150vh' is CSS's 150vh, which follows rotation and window resizes but not a phone's address bar (2.20.0). |
| top | number | 0 | Viewport Y (px) to pin at. 0 = top of viewport. |
| scrollContainer | string|Element | — | Custom scroll container. Default: window. |
| onEnter | () => void | — | Fires when scroll enters the pin zone (scrolling down). |
| onLeave | () => void | — | Fires when scroll exits the pin zone at the end. |
| onEnterBack | () => void | — | Fires when scroll re-enters the pin zone (scrolling up). |
| onLeaveBack | () => void | — | Fires when scroll exits the pin zone at the start. |
| onProgress | (p: number) => void | — | Progress 0–1 through the pin zone, every frame. |
destroy() restores the original DOM and removes all listeners. refresh() recalculates pin dimensions — call it after layout changes.Try it: Scroll a pinned feature tour in the scroll pin generator and copy its HTML, CSS and JS.
scrollSnap
JS-powered section snapping with custom easing and a configurable threshold. Works on vertical and horizontal axes with any scroll container. Unlike CSS scroll-snap-type, you get callbacks, programmatic control, and custom easing curves.
import { scrollSnap } from 'svg-scroll-draw/snap';
// Basic vertical snap between fullscreen sections
const snap = scrollSnap('.section', {
duration: 600,
easing: 'ease-in-out',
threshold: 0.3, // snap forward if user scrolled >30% of a section
onSnap: (index) => console.log('snapped to section', index),
});
// Horizontal snap (e.g. feature carousel). The cards scroll inside .carousel
// (overflow-x: auto); without scrollContainer it would snap the window sideways.
scrollSnap('.card', {
direction: 'horizontal',
scrollContainer: '.carousel',
duration: 400,
easing: 'ease-out',
onSnap: (i) => setActiveCard(i),
});
// Programmatic control
snap.snapTo(2); // scroll to section index 2
snap.getCurrentIndex(); // → current snapped index
// Cleanup
snap.destroy();| Option | Type | Default | Description |
|---|---|---|---|
| direction | "vertical" | "horizontal" | "vertical" | Scroll axis. |
| duration | number | 600 | Snap animation duration in ms. |
| easing | EasingName | fn | "ease-in-out" | Easing for the snap scroll animation. |
| threshold | number | 0.3 | Fraction of a section size the user must scroll past to snap forward (0–1). |
| scrollContainer | string | Element | — | Custom scroll container. Default: window. |
| respectReducedMotion | boolean | true | Honour prefers-reduced-motion by jumping straight to the target section. Snapping still happens — only the animated scroll is dropped. Tracked live, so toggling the OS setting takes effect without a reload. |
| onSnap | (index: number) => void | — | Fires after each snap with the target section index. Fires once per snap. |
Try it: Prefer plain scroll-snap-type? The CSS scroll snap generator builds a carousel or full-height sections with no JavaScript.
Scroll Callbacks
onEnter, onLeave, onEnterBack, and onLeaveBack are available on both scrollAnimate and scrollDraw. They fire exactly once per crossing — same semantics as GSAP ScrollTrigger.
import { scrollAnimate } from 'svg-scroll-draw';
// Activate/deactivate a section as it enters and leaves view
scrollAnimate('#feature-section', {
props: { opacity: [0.4, 1] },
trigger: { start: 'top center', end: 'bottom center' },
onEnter: () => nav.setActive('feature'), // scrolling down, entering
onLeave: () => nav.clearActive('feature'), // scrolling down, leaving
onEnterBack: () => nav.setActive('feature'), // scrolling up, re-entering
onLeaveBack: () => nav.clearActive('feature'), // scrolling up, leaving from top
});
// Lazy-load an image when it first enters view
scrollAnimate('#hero-img', {
props: { opacity: [0, 1] },
once: true,
onEnter: () => {
document.querySelector('#hero-img')
.setAttribute('src', '/hero.webp');
},
});animation-timeline fast path is skipped because callbacks require per-frame JavaScript.Lenis Adapter
Lenis needs no adapter. Every Lenis release so far is 1.x (2.0 exists only as development prereleases), and on every frame it moves the real scroll position: its setScroll() calls scrollTo(), so window.scrollY follows the eased scroll and every engine, the native CSS path included, works out of the box.
createLenisAdapter is for a scroller that keeps a virtual position and never moves the page: anything with Lenis’s on('scroll') / off('scroll') shape. It patches window.scrollY and window.pageYOffset to that value; pass native: false there, since CSS reads the real position. destroy() puts the browser’s own properties back (2.26.0+; before that it deleted them and left window.scrollY undefined).
// ── Lenis (no adapter needed) ─────────────────────────────────────
import Lenis from 'lenis';
import { scrollAnimate } from 'svg-scroll-draw';
const lenis = new Lenis();
function raf(time) {
lenis.raf(time);
requestAnimationFrame(raf);
}
requestAnimationFrame(raf);
// Lenis scrolls the real page, so svg-scroll-draw just works
scrollAnimate('#hero', { props: { opacity: [0, 1] }, once: true });
// ── A scroller that keeps a virtual position ──────────────────────
import { createLenisAdapter } from 'svg-scroll-draw/lenis';
// emits 'scroll' with { scroll, velocity, direction, progress }
const adapter = createLenisAdapter(scroller);
scrollAnimate('#hero', { props: { opacity: [0, 1] }, native: false });
// Cleanup: restores the browser's own window.scrollY
adapter.destroy();scrollAnimate
Animate any CSS property on any DOM or SVG element driven by scroll position. The direct replacement for gsap.to(el, { scrollTrigger }) for the 80% case.
import { scrollAnimate } from 'svg-scroll-draw';
// Fade + slide in
scrollAnimate('#hero-text', {
props: {
opacity: [0, 1],
transform: ['translateY(40px)', 'translateY(0px)'],
},
easing: 'ease-out',
once: true,
});
// Color transition
scrollAnimate('#section', {
props: {
backgroundColor: ['#ffffff', '#0d0d0d'],
color: ['#000000', '#ffffff'],
},
});
// React wrapper
import { ScrollAnimate } from 'svg-scroll-draw/react';
<ScrollAnimate
props={{ opacity: [0, 1], transform: ['translateY(24px)', 'translateY(0)'] }}
easing="ease-out"
once
>
<div>Any content</div>
</ScrollAnimate>| Option | Type | Default | Description |
|---|---|---|---|
| props | Record<string, …> | — | CSS properties to animate. Value can be a single target or [from, to] tuple. Supports numbers, colors (hex/rgb), transform functions, and CSS units. |
| trigger | TriggerConfig | { start: "top bottom", end: "bottom top" } | Same trigger syntax as scrollDraw. |
| easing | EasingName | fn | "ease-out" | Same easing system as scrollDraw. |
| speed | number | 1 | Animation scale factor. |
| once | boolean | false | Freeze at max progress — does not reverse on scroll back. |
| axis | "x" | "y" | "y" | Scroll axis. |
| native | boolean | true | Use CSS animation-timeline: view() fast path when eligible. |
| respectReducedMotion | boolean | true | Honour prefers-reduced-motion by applying the final state instead of animating, also when the reader turns it on while the page is open (2.22.0+). Set false only for scroll-linked scrubbing, which advances 1:1 with the user’s own scrolling rather than playing on its own. |
| triggerElement | Element | The animated element | Measure the trigger window from a different element. Needed when the animated element cannot supply the scroll length itself — a position:sticky element is only one viewport tall, so its window collapses to zero. Setting this disables the native CSS fast path, which can only measure its own subject. |
| onProgress | (n) => void | — | Called as the scroll moves, with alpha 0–1 (the first path’s, under stagger). |
| onComplete | () => void | — | Fires when alpha reaches 1. |
| onEnter | () => void | — | Fires when scroll enters the trigger zone (scrolling forward). Forces JS engine. |
| onLeave | () => void | — | Fires when scroll exits the trigger zone at the end (scrolling forward). |
| onEnterBack | () => void | — | Fires when scroll re-enters the trigger zone from the end (scrolling back). |
| onLeaveBack | () => void | — | Fires when scroll exits the trigger zone at the start (scrolling back). |
scrollCounter
Animate a number displayed in a DOM element from from to to as it scrolls into view.
import { scrollCounter } from 'svg-scroll-draw';
// Simple counter
scrollCounter('#user-count', { to: 50000 });
// Formatted with locale
scrollCounter('#revenue', {
to: 1_250_000,
format: n => '$' + Math.round(n).toLocaleString(),
easing: 'ease-out',
once: true,
});
// Percentage with one decimal. decimals replaces format, so the % goes in format.
scrollCounter('#conversion', {
from: 0,
to: 94.7,
format: n => n.toFixed(1) + '%',
});
// React
import { ScrollCounter } from 'svg-scroll-draw/react';
<ScrollCounter to={50000} format={n => n.toLocaleString()} once />Try it: Set from, to, decimals and a suffix in the counter animation generator and watch the number count before you copy it.
scrollParallax
Move any element at a different rate than scroll. speed is how far it travels while it crosses the viewport, as a fraction of its own size. A positive speed moves it up as you scroll down, so it runs ahead of the page: 0.5 = up half its height. A negative one moves it down, so it lags behind, like a background: -0.2 = down a fifth.
import { scrollParallax } from 'svg-scroll-draw';
scrollParallax('#hero-bg-image', { speed: 0.4 }); // ahead of the page
scrollParallax('#floating-element', { speed: -0.2 }); // lags behind the page
scrollParallax('#side-badge', { speed: 0.3, axis: 'x' }); // horizontalTry it: Give each layer its own speed in the parallax scrolling generator and scroll the scene to feel the depth.
scrollVideo
Tie a <video> element's currentTime to scroll position. The Apple product page pattern — ships free.
import { scrollVideo } from 'svg-scroll-draw/video';
// Full scrub — plays as user scrolls through section
scrollVideo('#hero-video', {
trigger: { start: 'top top', end: 'bottom top' },
});
// Scrub only the first 3 seconds
scrollVideo('#product-reveal', {
from: 0,
to: 3,
trigger: { start: 'top 80%', end: 'top 20%' },
easing: 'ease-in-out',
});
// A pinned film: the video sits in a sticky stage inside a tall track,
// so measure the track — the video's own box moves while it is stuck (2.18.0)
scrollVideo('#film', {
triggerElement: document.querySelector('#film-track'),
trigger: { start: 'top top', end: 'bottom bottom' },
});
// React: preload follows the option, poster goes to the <video> (2.23.4)
import { ScrollVideo } from 'svg-scroll-draw/react';
<ScrollVideo src="/hero.mp4" poster="/hero.jpg" trigger={{ start: 'top top', end: 'bottom top' }} />Encoding: put a keyframe every few frames (-g 3): measured in Chromium, that kept every seek under 7.3 ms, where one keyframe for the whole clip took up to 53.6 ms. Serve the file from a server that answers Range requests, or it will not seek at all, and add muted playsinline preload="auto". The whole pinned-film build is the Scroll-video recipe.
Try it: Set the pin, range and easing on your own clip in the scroll video scrub generator.
scrollFrames
The same film drawn one still at a time: frame round(progress × (count − 1)) of a numbered image sequence, painted on a <canvas> as you scroll. A video seeks to a keyframe and decodes forward; a decoded image shows at once, in every browser. 4.5 KB gzipped for its entry.
import { scrollFrames } from 'svg-scroll-draw/frames';
// 120 frames: /film/0001.jpg … /film/0120.jpg
scrollFrames('#film', {
frames: (i) => `/film/${String(i + 1).padStart(4, '0')}.jpg`,
count: 120,
});
// Pinned: the canvas in a sticky stage, the track measured
scrollFrames('#film', {
frames: urls, // or a list of URLs
fit: 'contain', // the whole frame; 'cover' (default) fills and crops
triggerElement: document.querySelector('#film-track'),
trigger: { start: 'top top', end: 'bottom bottom' },
});Size the canvas with CSS: its drawing buffer follows the box × devicePixelRatio (capped at 2). Frame 0 loads first, then the last, then the middle of every gap, concurrency (6) at a time; until a frame arrives, the nearest loaded one shows. Under reduced motion only the last frame is loaded and drawn. The library adds no ARIA: give the canvas role="img" and an aria-label. In React and Vue (2.25.0+), <ScrollFrames> (from svg-scroll-draw/react or /vue) renders the canvas with role="img", takes every option as a prop and stops the film when it unmounts; an inline frames function is compared by the URLs it gives, so a re-render keeps the film. In Svelte, Solid and Angular (2.26.0+) it binds to a canvas you write, with the same rules: use:scrollFramesAction={{ frames, count }} (or createScrollFrames) from svg-scroll-draw/svelte, <canvas ref={useScrollFrames(() => ({ frames, count }))} /> from svg-scroll-draw/solid, and new ScrollFramesRef() from svg-scroll-draw/angular with init, update and destroy from its lifecycle hooks; triggerElement also takes a selector there. The whole pinned build, on 71 real frames, is the Scroll image sequence recipe.
Try it: Turn a video into frames and scrub them, pinned or in the flow, in the scroll image sequence generator.
scrollText
Split any text element into chars, words, or lines and animate each piece on scroll. A 3.9 KB alternative to GSAP SplitText. SplitText is free and 3.6 KB, but it only splits — animating the pieces needs GSAP core (27.7 KB) too.
import { scrollText } from 'svg-scroll-draw/text';
// Words fade up one by one
scrollText('#headline', {
split: 'words',
stagger: 0.05,
from: { opacity: 0, y: 24 },
easing: 'ease-out',
once: true,
});
// Characters with rotation
scrollText('#tagline', {
split: 'chars',
stagger: 0.025,
from: { opacity: 0, y: 32, rotate: 8 },
once: true,
});
// React
import { ScrollText } from 'svg-scroll-draw/react';
<ScrollText split="words" stagger={0.05} from={{ opacity: 0, y: 24 }} once>
Animate this headline.
</ScrollText>Accessibility: the element keeps one visually hidden copy of its whole text, after the split pieces, so a screen reader reads the sentence once. All split spans have aria-hidden="true". No aria-label is added: ARIA does not allow one on a paragraph or a span. destroy() restores the original HTML.
Try it: Split a line by word, letter or line in the text animation generator, or type it out letter by letter in the typewriter effect generator.
DevTools Overlay
Visual debug overlay that shows every active animation's trigger window, current progress, and type — color-coded in a fixed panel. Zero production bytes (tree-shaken away in production builds).
import { devtools } from 'svg-scroll-draw/devtools';
// Enable once — instruments all active instances
devtools.enable();
// Keyboard shortcut: Cmd+Shift+S / Ctrl+Shift+S to toggle
// Or toggle programmatically:
devtools.toggle();
// Highlight a specific element for 2 seconds
devtools.highlight('#my-animated-element');Note: The devtools panel only activates when process.env.NODE_ENV !== 'production'. In production builds, the import resolves to a no-op.
Types Reference
All types are exported from the root package — import them alongside your runtime imports.
import type {
ScrollDrawOptions,
ScrollDrawInstance,
EasingName,
TriggerConfig,
} from 'svg-scroll-draw';
type EasingName = 'linear' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'spring';
interface TriggerConfig {
start?: string;
end?: string;
}
interface ScrollDrawInstance {
destroy: () => void;
replay: () => void;
pause: () => void;
resume: () => void;
seek: (progress: number) => void;
getProgress: () => number;
}
interface ScrollDrawOptions {
selector?: string;
speed?: number;
fade?: boolean;
easing?: EasingName | ((t: number) => number);
trigger?: TriggerConfig;
stagger?: number;
direction?: 'forward' | 'reverse';
once?: boolean;
debug?: boolean;
axis?: 'x' | 'y';
scrollContainer?: string | Element;
autoReverse?: boolean;
delay?: number;
strokeColor?: string | [string, string];
strokeWidth?: number | [number, number];
fillOpacity?: number | [number, number];
clip?: boolean | 'left' | 'right' | 'top' | 'bottom' | 'center';
waypoints?: Record<number, () => void>;
velocityScale?: boolean | number;
threshold?: number;
rootMargin?: string;
repeat?: number | 'infinite';
repeatDelay?: number;
morphTo?: string;
onProgress?: (alpha: number) => void;
onStart?: () => void;
onComplete?: () => void;
native?: boolean;
}