pathLength使得SVG路径动画更易于管理

You've probably seen this SVG effect that people use to animate signatures. If you have an SVG path you can combine stroke-dasharray, stroke-dashoffset and CSS animations/transitions to animate a given SVG path. Here's an example of the effect.

你可能见过人们用来动画签名的这个 SVG 效果。如果你有一个 SVG 路径,你可以结合 stroke-dasharraystroke-dashoffset 和 CSS 动画/过渡来动画化给定的 SVG 路径。这里是这个效果的一个例子。

The SVG includes a single SVG path that expands when you hover over the SVG. How does this work in detail?

该 SVG 包含一个单一的 SVG 路径,当你将鼠标悬停在 SVG 上时,它会扩展。这是如何详细工作的呢?

As a first step, you can cut SVG paths into visual pieces with stroke-dasharray. It's important to know that the "drawn pieces" and in-between gaps will have the same length.

作为第一步,你可以使用 stroke-dasharray 将 SVG 路径切割成可视的片段。重要的是要知道,“绘制的片段”和之间的间隙将具有相同的长度。

Then, after you've chopped your path into pieces, you can move these pieces around the SVG path with stroke-dashoffset.

然后,在你将路径切割成片段后,你可以使用 stroke-dashoffset 在 SVG 路径中移动这些片段。

So, the overall trick is to make the pieces as big as the entire path length to transition from showing a gap (which spans the entire path) to showing a drawn piece next to it.

所以,整体的技巧是将片段的大小设置为整个路径的长度,以便从显示一个跨越整个路径的间隙过渡到显示一个相邻的绘制片段。

If you played with the demo above, you might have wondered where this magic number (14302) is coming from. 14302 is the overall path length, and you can access it with some JavaScript.

如果你玩过上面的演示,你可能会想知道这个神奇的数字 (14302) 是从哪里来的。 14302 是整体路径长度,你可以通过一些 JavaScript 访问它。

const path = document.querySelector('path');
const pathLength = path.getTotalLength();

With the path length available, you can then write some quick CSS to achieve this effect.

有了路径长度后,你可以写一些快速的 CSS 来实现这个效果。

path {
  /* Cut the path into pieces being as long as the path itself */
  stroke-dasharray: 14301;
  /* Move the rendering to the gap */
  stroke-dashoffset: 14301;
  transition: stroke-dashoffset 0.75s ease-in-out;
  
  &:hover {
    /* Transition the offset to show the rendered path piece */
    stroke-dashoffset: 0;
  }
}

And while this approach works just fine, it's a bit cumbersom...

开通本站会员,查看完整译文。

Accueil - Wiki
Copyright © 2011-2025 iteam. Current version is 2.147.1. UTC+08:00, 2025-11-09 04:27
浙ICP备14020137号-1 $Carte des visiteurs$