本文详解如何使用原生 css + javascript 实现 svg 文字路径的「滚动进入视口时单次绘制动画」,无需第三方库,核心基于 `gettotallength()`、`stroke-dasharray`/`stroke-dashoffset` 与 intersection observer api。
实现类似 weaintplastic.com 首屏 SVG 文字的“逐字手绘感”动画,关键不在于为每个字母写独立 CSS,而在于将 SVG 中的
向下滚动,查看动画效果
/* 必须设置 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`; */// 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);
});你无需为每个字母写独立 CSS 或 JS —— 通过 getTotalLength() 动态获取路径长度,配合 stroke-dasharray/
stroke-dashoffset 的「虚线遮罩动画」,再用 Intersection Observer 精准控制触发时机,即可优雅实现专业级 SVG 滚动绘制效果。整个方案轻量、可维护、无外部依赖,真正“一次配置,处处复用”。