滚动绘图

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 免费的 200 美元信用额度!

我们之前深入探讨了 SVG 线条绘制的工作原理。这是一个巧妙的技巧,你使用虚线绘制描边,但虚线之间的间隙很长,覆盖了整个路径。然后你可以移动它,使其再次覆盖整个路径,从而看起来像是它在自行绘制。

使用一些 JavaScript,我们可以做得更花哨一些,在页面滚动到底部时绘制出完整的形状。

演示

查看 CodePen 上 Chris Coyier 的笔 滚动绘图 (@chriscoyier) on CodePen.

步骤 1:获取 <path>

它必须是 <path>。任何其他类型的 SVG 元素都不起作用(例如 <rect>)。不过,你可以强制元素成为路径。我有一个关于 Lodge 视频 的视频。你可能需要采取一些技巧,比如在已经笔直的边缘添加额外的矢量点。

在我的演示中,我只是直接从 Illustrator 中复制粘贴了形状。

如果路径没有 ID,则为其指定一个 ID

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100.6 107.6" id="star-svg">
  <path id="star-path" fill="none" stroke="black" stroke-width="2"  d=" ... " />
</svg>

步骤 2:查找路径的长度

// Get a reference to the <path>
var path = document.querySelector('#star-path');

// Get length of path... ~577px in this demo
var pathLength = path.getTotalLength();

步骤 3:通过偏移虚线来隐藏形状

// Make very long dashes (the length of the path itself)
path.style.strokeDasharray = pathLength + ' ' + pathLength;

// Offset the dashes so the it appears hidden entirely
path.style.strokeDashoffset = pathLength;

步骤 4:页面滚动时,偏移虚线与滚动百分比相同

// When the page scrolls...
window.addEventListener("scroll", function(e) {
 
  // What % down is it? 
  var scrollPercentage = (document.documentElement.scrollTop + document.body.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);
    
  // Length to offset the dashes
  var drawLength = pathLength * scrollPercentage;
  
  // Draw in reverse
  path.style.strokeDashoffset = pathLength - drawLength;
  
});

步骤 5:如果滚动到底部,则移除虚线

如果你这样做,形状看起来不像你没有应用任何虚线那样整洁/清晰地完成。

我不确定为什么。我认为你无法调整数字来修复它。但移除它很容易。

  // ... at bottom of scrolling function

  // When complete, remove the dash array, otherwise shape isn't quite sharp
  if (scrollPercentage >= 0.99) {
    path.style.strokeDasharray = "none";
  } else {
    path.style.strokeDasharray = pathLength + ' ' + pathLength;
  }

0.99 是为了弥补模糊的数学。有时你无法从除法中得到完美的 1.0。


查看完整页面演示。