使用 GSAP 将 SVG 元素复制到 DOM

Insert copies SVG elements into DOM with GSAP

我正在尝试使用 TweenMax 和 TimelineMax 为页面上的多个 circle 元素制作动画。实际的 SVG 只有这个特定 circle 元素的一个实例,但我希望动画序列以相同的指定过渡为这些相同元素中的几个设置动画。

是否可以 'copy' 一个 SVG 元素并执行交错动画?

例如:

function makeFiveCopies() {
  // return array of five identical 'circle' elements
}

var circles = makeFiveCopies($('circle'));

var tl = new TimelineMax();

tl.staggerTo(circles, 2, { yPercent: 300 });

tl.play();

是否可以用 Greensock 做这样的事情,或者我是否必须使用 SVG 编辑器将元素的几个相同副本实际插入到 SVG 中?

http://codepen.io/himmel/pen/qOmpGm

如果您查看此 CodePen 示例,您会发现我正在使用 JavaScript 动态创建 SVG <circle> 标签。然后我用 GSAP 交错动画。

http://codepen.io/jonathan/full/EVgYbB

codepen 编辑器模式下的示例:

http://codepen.io/jonathan/pen/EVgYbB

您必须使用 createElementNS 而不是 createElement,因为 SVG 要求您指定命名空间 URI。

createElementNS: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS

创建元素: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

HTML:

<svg id="box"></svg>

只是循环中的一个例子,JS:

var $box = document.getElementById("box"); // main SVG tag
var svgNS = "http://www.w3.org/2000/svg";

var circleCount = 25;    

for (var i = 0; i < circleCount; i++) {

   var circle = document.createElementNS(svgNS, 'circle');

   var r = (i + 2) * 4;
   var cx = mainW;
   var cy = mainH;

   circle.setAttributeNS(null, "id", "circle" + i);
   circle.setAttributeNS(null, "cx", cx);
   circle.setAttributeNS(null, "cy", cy);
   circle.setAttributeNS(null, "r", r);

   $box.appendChild(circle);
}