
本文详解如何使用原生 css + javascript 实现 svg 文字路径的「滚动进入视口时单次绘制动画」,无需第三方库,核心基于 `gettotallength()`、`stroke-dasharray`/`stroke-dashoffset` 与 intersection observer api。
实现类似 weaintplastic.com 首屏 SVG 文字的“逐字手绘感”动画,关键不在于为每个字母写独立 CSS,而在于将 SVG 中的
✅ 核心原理简明说明
- stroke-dasharray:定义虚线模式,设为 length 即「一条实线 + 无限空白」,视觉上完全不可见;
- stroke-dashoffset:控制虚线起始位置,初始设为 length,使整条线向右偏移至完全隐藏;动画中将其归零,等效于“从左向右画出”;
-
getTotalLength():动态获取每条
的精确长度(单位 px),避免手动计算误差; -
Intersection Observer:监听目标元素(如
)进入视口的瞬间,仅触发一次动画,符合“scroll once”需求。
? 完整实现代码(可直接复用)
HTML 结构(含 SVG)
向下滚动,查看动画效果
CSS 样式(关键动画逻辑)
/* 必须设置 stroke 才能生效 */
svg path {
fill: none;
stroke: #000; /* 描边颜色 */
stroke-width: 1.2; /* 线宽,影响动画粗细 */
stroke-linecap: round;
stroke-linejoin: round;
}
/* 默认隐藏所有路径 */
.trigger-section svg path {
stroke-dasharray: 0;
stroke-dashoffset: 0;
transition: none; /* 防止初始闪动 */
}
/* 动画触发类(由 JS 添加) */
.trigger-section.animate svg path {
animation: draw-letter 2s ease-out forwards;
}
@keyframes draw-letter {
to {
stroke-dashoffset: 0;
}
}
/* 可选:为每个字母添加错峰动画(增强手绘感) */
.trigger-section.animate svg path:nth-child(1) { animation-delay: 0.1s; }
.trigger-section.animate svg path:nth-child(2) { animation-delay: 0.2s; }
/* 或更灵活地用 JS 动态设置:path.style.animationDelay = `${i * 0.15}s`; */JavaScript(自动初始化 + 滚动监听)
// 1. 初始化所有路径:计算长度并隐藏
document.querySelectorAll('.trigger-section svg path').forEach((path, i) => {
const length = path.getTotalLength();
path.style.strokeDasharray = `${length}`;
path.style.strokeDashoffset = `${length}`;
path.style.animationDelay = `${i * 0.15}s`; // 错峰启动
});
// 2. 使用 IntersectionObserver 监听进入视口
const observer = new IntersectionObserver(
(entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('animate');
observer.unobserve(entry.target); // ✅ 关键:只执行一次
}
});
},
{ threshold: 0.1 } // 当 10% 进入视口即触发
);
// 3. 开始观察所有目标 section
document.querySelectorAll('.trigger-section').forEach(section => {
observer.observe(section);
});⚠️ 注意事项与最佳实践
-
SVG 要求:确保
元素无 fill(或设为 none),且有明确 stroke;避免使用 标签——需先转为路径(Illustrator 中「创建轮廓」); - 性能优化:getTotalLength() 在首次调用时会触发 layout,建议在 DOM 加载完成后立即执行(如 DOMContentLoaded);
- 响应式适配:若 SVG 需缩放,getTotalLength() 返回的是当前渲染尺寸,无需额外处理;
- 无障碍友好:为 SVG 添加 aria-hidden="true"(纯装饰),重要内容仍需保留语义化文本;
- 浏览器兼容性:Intersection Observer 在现代浏览器中支持良好;如需支持 IE,可用 intersection-observer polyfill。
✅ 总结
你无需为每个字母写独立 CSS 或 JS —— 通过 getTotalLength() 动态获取路径长度,配合 stroke-dasharray/stroke-dashoffset 的「虚线遮罩动画」,再用 Intersection Observer 精准控制触发时机,即可优雅实现专业级 SVG 滚动绘制效果。整个方案轻量、可维护、无外部依赖,真正“一次配置,处处复用”。










