我们之前深入探讨了 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。
哈哈,我刚好在 Treehouse 上完成了“使用 CSS 动画 SVG”课程的这一部分(目前正在享受这门课程)。虚线描边技巧非常巧妙,期待着尝试一下。不过,之前没有想到用 JS 动态改变值——很不错!
很棒,谢谢
在 iOS 上似乎不起作用
我用 SVG 工作过几次,Safari 无法渲染 SVG 路径 :(
我在 Safari 8.0.7(10600.7.12)中尝试过,它运行良好。必须使用鼠标滚轮或其他方法在窗口中滚动。
还没有在 iOS 中尝试过。
这很棒。我尝试在我的网站上添加它,但它似乎在 IE8 和 Safari 中不起作用。有什么建议吗?
抱歉,网站是 http://fredamiklingv.com
IE8 不支持 SVG。
放弃对 IE8 的支持!!!
谢谢,我一直在寻找类似的东西,大约一个月了