中文
一条路怎么走到海边
Scroll · Vanilla JS + CSS

Scroll line drawing

滚动描线绘制

Draw an SVG line as the page scrolls.

Also searched as: 往下滑时一条线一路画出来, 滚动时线条跟着一笔一笔描出来, 随着滚动画线, 滑到哪里线就画到哪里

AI Markdown (.md)
Placement
Article, Image
Mood
Soft, Refined
Trigger
Scroll
Site types
个人网站, 作品集, 博客

How it works & accessibility

Give each stroked shape pathLength=1 and stroke-dasharray: 1, then map the drawing's position between a start and an end point in the viewport to stroke-dashoffset (1 minus progress), updating at most once per frame while scrolling; without JavaScript or with reduced motion the line stays fully drawn.

Best for: Article, Image (Scroll).

Reduced motion: 不跟着滚动画,线一直是画完的样子

Mobile & touch: 和桌面一样;手机屏幕矮,开始和画完的位置靠近一点(比如 85% 和 45%),线不会画得太快

Key parameters

ParameterKeyDefaultRangeNotes
开始画的位置(屏幕从上往下)start80%——
画完的位置(屏幕从上往下)end30%——

Ready-to-paste AI prompt

Add “Scroll line drawing” to the article in my project: Give each stroked shape pathLength=1 and stroke-dasharray: 1, then map the drawing's position between a start and an end point in the viewport to stroke-dashoffset (1 minus progress), updating at most once per frame while scrolling; without JavaScript or with reduced motion the line stays fully drawn.
Parameters: start: 80%, end: 30%.
Preserve existing content and layout. Respect prefers-reduced-motion by showing the final state. Content must remain visible if JavaScript fails or is disabled.
Reference: https://donglang.linter.top/effects/scroll-line-draw.md (canonical specification and reference code).

Dependency-free reference code

CSS
/* 滚动描线绘制不需要额外的样式:stroke-dasharray、stroke-dashoffset 只由脚本写在线的行内样式上。
   CSS 里不要写 stroke-dasharray:没有脚本、脚本出错、开了减少动态时,线照样是画完的。线的粗细、颜色、圆头照你的设计写在 SVG 上。 */
JavaScript
// 滚动描线绘制(Scroll line drawing)· 原生 JS,不依赖任何库。
// 参考 Animation Handbook 的 svg-line-draw、Motion Lexicon 的 line-drawing 的做法(都是 MIT),自己实现,没有复制代码。
// 用法:scrollLineDraw(svg),返回 { update(), destroy() }。svg 里的图形(path、line、polyline、polygon、circle、ellipse、rect;藏在 defs、clipPath、mask、pattern、marker、symbol 里的不算)都当成"线",
// 一起跟着滚动画出来。给每条线临时设 pathLength="1"(线的总长就当 1)、行内 stroke-dasharray: 1,stroke-dashoffset 从 1(没画)走到 0(画完)。
// 进度 k = clamp((H × start/100 − 上边) / (高 + H × (start − end)/100), 0, 1):H 是屏幕(或 root 框)的可视高,上边、高是 svg 的框相对屏幕(框)上边的位置和高度——
// 图形的上边到了屏幕从上往下 start% 处开始画,下边到了 end% 处画完;stroke-dashoffset = 1 − k。
// 选项:start、end 写百分数(80 就是 80%,和数据里一样);start 要比 end 大(开始画的位置在画完的位置上面),数据里的范围已经分开;root 是滚动的容器,默认整个页面(window),放在自己会滚动的框里时传那个框。
// 滚动(passive)里只排一次逐帧更新,同一帧里再多次滚动也只算一次;改窗口大小、svg 或滚动框自己变大小时也重算;update() 手动重算一次。
// 开启"减少动态"时:不监听滚动、不排逐帧更新,线是画完的样子(不碰行内样式);ignoreReducedMotion 只给演示强制播放用。
// 没有脚本、脚本出错时线是画完的(CSS 里不写 stroke-dasharray,只有脚本写)。
// destroy():摘掉所有监听、取消排好还没跑的逐帧更新、把每条线的行内样式和 pathLength 还原,之后 update() 什么都不做;对同一个 svg 重复调用,先 destroy 旧的。

// 每个 svg 现在装着的控制对象(对同一个 svg 重复调用时先拆旧的)
const prevs = new WeakMap();
const SHAPES = 'path, line, polyline, polygon, circle, ellipse, rect';

export function scrollLineDraw(svg, {
  start = 80,
  end = 30,
  root = window,
  ignoreReducedMotion = false,
} = {}) {
  prevs.get(svg)?.destroy();
  const nothing = { update() {}, destroy() {} };
  if (!ignoreReducedMotion && matchMedia('(prefers-reduced-motion: reduce)').matches) return nothing;
  // defs、clipPath、mask、pattern、marker、symbol 里的图形不是画出来的线(是别处引用的模板),不算
  const lines = [...svg.querySelectorAll(SHAPES)].filter((el) => !el.closest('defs, clipPath, mask, pattern, marker, symbol')).map((el) => ({ el, style: el.getAttribute('style'), length: el.getAttribute('pathLength') }));
  if (!lines.length) return nothing;
  for (const { el } of lines) {
    el.setAttribute('pathLength', '1');
    el.style.strokeDasharray = '1';
  }
  let dead = false;
  let frame = 0;

  // 屏幕(或滚动框里看得见的那一块)的上边和高度
  const view = () => {
    if (root === window) return [0, innerHeight];
    const r = root.getBoundingClientRect();
    return [r.top + root.clientTop, root.clientHeight];
  };
  const update = () => {
    if (dead) return;
    const [top, height] = view();
    const r = svg.getBoundingClientRect();
    const begin = (height * start) / 100;
    const span = r.height + (height * (start - end)) / 100;
    const at = r.top - top;
    const k = span > 0 ? Math.min(1, Math.max(0, (begin - at) / span)) : at <= begin ? 1 : 0;
    const offset = (1 - k).toFixed(4);
    for (const { el } of lines) el.style.strokeDashoffset = offset;
  };
  const schedule = () => {
    if (dead || frame) return;
    frame = requestAnimationFrame(() => { frame = 0; update(); });
  };
  root.addEventListener('scroll', schedule, { passive: true });
  window.addEventListener('resize', schedule, { passive: true });
  const resized = new ResizeObserver(schedule);
  resized.observe(svg);
  if (root !== window) resized.observe(root);
  update();

  const ctl = {
    update,
    destroy() {
      if (dead) return;
      dead = true;
      cancelAnimationFrame(frame);
      frame = 0;
      root.removeEventListener('scroll', schedule);
      window.removeEventListener('resize', schedule);
      resized.disconnect();
      for (const { el, style, length } of lines) {
        // 先摘掉自己写的两项,再还原原来的行内样式(原来没有 style 属性的,摘完是空的就把属性去掉)
        el.style.removeProperty('stroke-dasharray');
        el.style.removeProperty('stroke-dashoffset');
        if (style !== null) el.setAttribute('style', style);
        else if (!el.getAttribute('style')) el.removeAttribute('style');
        if (length === null) el.removeAttribute('pathLength'); else el.setAttribute('pathLength', length);
      }
      if (prevs.get(svg) === ctl) prevs.delete(svg);
    },
  };
  prevs.set(svg, ctl);
  return ctl;
}
HTML
<!-- 滚动描线绘制:文章里的一张 SVG 插图,里面每一条有描边的线都会跟着滚动画出来;没有脚本时线是画完的 -->
<figure class="sketch">
  <svg id="sketch" viewBox="0 0 400 200" width="100%" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round">
    <path d="M10 150 C 80 20, 160 20, 200 100 S 330 180, 390 40" />
    <circle cx="200" cy="100" r="24" />
  </svg>
  <figcaption>往下滑时线一路画出来</figcaption>
</figure>
<script type="module">
  import { scrollLineDraw } from './scroll-line-draw.js';
  scrollLineDraw(document.getElementById('sketch'), { start: 80, end: 30 });
</script>

Shown once per release · Always available in changelog