【问题标题】:Animate SVG path via javascript通过 javascript 动画 SVG 路径
【发布时间】:2015-05-28 21:26:55
【问题描述】:

我想通过按钮点击动画 svg 路径,但它不起作用。

<svg width="100" height="50">
    <path id="path1" d="M 10 10  L 40 20  20 40" fill="none" stroke="blue" stroke-width="2"  />
</svg>
<button type="button" id="btn">Change</button>
<script>
    var btn = document.getElementById('btn');
    btn.onclick = function () {
        var path = document.getElementById('path1');
        var animate = document.createElementNS("http://www.w3.org/2000/svg","animate");
        animate.setAttribute('attributeName', 'd');
        animate.setAttribute('dur', 's');
        animate.setAttribute('fill', 'freeze');
        animate.setAttribute('values', 'M 10 10  L 40 20  20 40; M 30 10  L 10 40  40 30');
        path.appendChild(animate);
    }
</script>

http://jsfiddle.net/c5mzn6d0/

如果您在页面加载后立即按下“更改”按钮,则会出现动画。但是如果你在页面加载后等待4秒(属性dur中指定的时间)并按下按钮,没有动画。如果您等待 2 秒并按下按钮,动画将从中间开始。

如何通过 javascript 更正动画 SVG 路径的“d”属性?

【问题讨论】:

  • 尝试将动画作为&lt;animateMotion begin="btn.click" path="M 10 10 L 40 2...添加到html内的svg并删除按钮点击处理程序。

标签: javascript animation svg


【解决方案1】:

http://jsfiddle.net/c5mzn6d0/4/

添加

animate.beginElement();

添加动画后:

var btn = document.getElementById('btn');
btn.onclick = function () {
    var path = document.getElementById('path1');
    var animate = document.createElementNS("http://www.w3.org/2000/svg","animate");
    animate.setAttribute('attributeName', 'd');
    animate.setAttribute('dur', '1s');
    animate.setAttribute('fill', 'freeze');
    animate.setAttribute('values', 'M 10 10  L 40 20  20 40; M 30 10  L 10 40  40 30');
    path.appendChild(animate);
    animate.beginElement();
}

【讨论】:

    猜你喜欢
    • 2013-01-27
    • 2016-02-14
    • 2016-01-06
    • 2013-02-20
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2013-01-28
    相关资源
    最近更新 更多