具有多个SVG <animate>的

时间:2019-07-27 17:35:44

标签: javascript animation svg safari

我正在尝试对多边形上具有多个<animate>标签的SVG播放停止按钮进行动画处理,以便在每个beginElement()上运行<animate>会使形状变形其点。这在Chrome和Firefox上效果很好,但是在Safari中测试时,我似乎只能激活一个<animate>标签。

我目前所拥有的如下:

playState = true;

function toggle() {
  playState = !playState;
  document.querySelector("#to" + (playState ? "Play" : "Stop")).beginElement();
  console.log("Changed state to " + (playState ? "play" : "stop") + ".")
}

document.querySelector("#toggle").addEventListener("click", toggle);

toggle();
#toggle circle {
  fill: #808080;
}

#toggle polygon {
  fill: #DCDCDC;
}
<svg id="toggle" viewBox="0 0 300 300">
        <circle cx="150" cy="150" r="100"/>

<polygon points="150,150 150,150 150,150 150,150">
    <animate fill="freeze" id="toStop" attributeName="points" dur="500ms" to="100,100 100,200 200,200 200,100" begin="indefinite"     calcMode      = "spline"
    keySplines    = "0 0.75 0.25 1"
    keyTimes      = "0;1"/>
     <animate fill="freeze" id="toPlay" attributeName="points" dur="500ms" to="120,100 120,200 206.6025403784,150 206.6025403784,150" begin="indefinite"     calcMode      = "spline"
    keySplines    = "0 0.75 0.25 1"
    keyTimes      = "0;1"/>
    </polygon>

</svg>

在Safari中进行测试时,我最初可以正确触发#toPlay,但是随后,在两个状态之间的beginElement()上运行#toPlay时会闪烁,然后激活#toStop则无济于事。好像#toStop动画被延迟,然后在再次触发#toPlay时迅速运行。

1 个答案:

答案 0 :(得分:1)

我自己弄清楚了!但是,我被迫稍作妥协。 Jesus CMD explains,您需要在每次beginElement()的其他每次调用中重置SVG动画。该解决方案的缺点是必须将动画重置为多边形点的初始值,因此我希望具有三种可能的多边形形状(单点,正方形和三角形)是缩小到只有两个状态:播放和停止。

已更改的代码段如下。

playState = true;
svg = document.querySelector("#toggle");

function toggle() {
  playState = !playState;
  if (playState) {

    svg.pauseAnimations();
    svg.setCurrentTime(0);
    svg.unpauseAnimations();
    document.querySelector("#toPlay").beginElement();
  } else {
    document.querySelector("#toStop").beginElement();
  }
  //document.querySelector("#to" + (playState ? "Play" : "Stop")).beginElement();
  console.log("Changed to " + (playState ? "Play" : "Stop"))
}

svg.addEventListener("click", toggle);
toggle();
#toggle circle {
  fill: #808080;
}

#toggle polygon {
  fill: #DCDCDC;
}
<svg id="toggle" viewBox="0 0 300 300">
        <circle cx="150" cy="150" r="100"/>

<polygon points="100,100 100,200 200,200 200,100">
    <animate fill="freeze" id="toStop" attributeName="points" dur="500ms" to="100,100 100,200 200,200 200,100" begin="indefinite"     calcMode      = "spline"
    keySplines    = "0 0.75 0.25 1"
    keyTimes      = "0;1"/>
     <animate fill="freeze" id="toPlay" attributeName="points" dur="500ms" to="120,100 120,200 206.6025403784,150 206.6025403784,150" begin="indefinite"     calcMode      = "spline"
    keySplines    = "0 0.75 0.25 1"
    keyTimes      = "0;1"/>
    </polygon>

</svg>