如何动画到SVG的所有路径

时间:2017-07-20 18:08:59

标签: animation svg svg-animate

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

1 个答案:

答案 0 :(得分:1)

重新创建此效果非常简单。

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

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

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

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

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

然后,对于动画,我们逐个遍历所有<path>元素(有延迟),添加一个使用transform的类来将路径移回屏幕。

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

转换导致路径平滑滑动。

工作演示

&#13;
&#13;
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);
&#13;
/* 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;
}
&#13;
<svg width="400" height="400" viewBox="0 0 100 100">
  <g id="anim"></g>
</svg>
&#13;
&#13;
&#13;