如何动画到SVG的所有路径

How to animation to all path of SVG

我想为 SVG 制作动画并延迟任何元素。 请参阅此 link 和狮子 SVG。 这个动画很简单,但是延迟到任何路径都非常耗时。

重现此效果非常简单。

我没有查看该网站是如何做到的,但我会这样做。

首先我们需要一个所有路径都在一个组中的 SVG (<g>);

<svg>
  <g id="anim">
    <!-- path elements in here -->
  </g>
</svg>

在页面加载时,我们在组上设置一个变换,将其(所有路径)移出 SVG 的一侧。

group.setAttribute("transform", "translate(-100, 0)");

然后,对于动画,我们一个接一个(有延迟)循环遍历所有 <path> 元素,添加一个 class 使用 transform 将路径移回在屏幕上。

.onto-screen-anim
{
  transition: transform 1s ease-out;
  transform: translateX(100px);  /* 100 = width of viewBox */
}

过渡使路径平滑地滑入。


工作演示

var group = document.getElementById("anim");


// Generate a lot of test paths in our SVG.
// This is just for the demo as an alternative to having a big SVG in our snippet.
for (var i=0; i<100; i++) {
  path = document.createElementNS("http://www.w3.org/2000/svg", "path");
  var r1 = 5 + Math.random() * 45;
  var r2 = 5 + Math.random() * 45;
  var a1 = Math.random() * 2 * Math.PI;
  var a2 = a1 + (Math.random() - 0.5);
  path.setAttribute("d", [
    'M', 50 + Math.cos(a1) * r1, 50 + Math.sin(a1) * r1,
    'L', 50 + Math.cos(a2) * r2, 50 + Math.sin(a2) * r2,
  ].join(' '));
  group.appendChild(path);
}


// Add a transform to the<svg> root element to move all the child
// elements off the left edge of the SVG where we want them to start.
// The value 100 represents the width of the viewBox.
group.setAttribute("transform", "translate(-100, 0)");


// For our animation, just loop through all paths, adding the 
// "onto-screen-anim" class that moves them back into view.

var INTER_PATH_DELAY = 16;   // 10 milliseconds

var allPaths = group.querySelectorAll("path");
var itemNum = 0;
function startOnePathMoving() {
  // Add the class that moves the path onto screen
  allPaths[itemNum++].classList.add("onto-screen-anim");
  // if there are paths left, then call this function again
  // after a short delay to start the next one moving
  if (itemNum < allPaths.length)
    setTimeout(startOnePathMoving, INTER_PATH_DELAY);
}

// Start the first timeout to get the animation started
setTimeout(startOnePathMoving, INTER_PATH_DELAY);
/* Make sure the paths that are off the SVG can't be seen */
svg {
  overflow: hidden;
}

/* The class that moves the paths back onto screen */
.onto-screen-anim
{
  transition: transform 1s ease-out;
  transform: translateX(100px);  /* 100 = width of viewBox */
}

/* Styling for our demo paths. You can ignore this for a real SVG */
path {
  fill: none;
  stroke: grey;
  stroke-width: 0.5;
}
<svg width="400" height="400" viewBox="0 0 100 100">
  <g id="anim"></g>
</svg>