gpt4 book ai didi

javascript - 使用 CSS 过渡动画动态 SVG 属性

转载 作者:搜寻专家 更新时间:2023-10-31 08:43:45 24 4
gpt4 key购买 nike

我正在尝试使用 JavaScript 和 CSS 转换为各种 SVG 形状的属性设置动画。

例如:

HTML:

<svg width="400" height="400">
<circle id="circle" cx="200" cy="200" r="15" stroke="none" fill="blue" />
<rect id="rect" x="100" y="100" height="30" width="30" stroke="none" fill="red" />
</svg>
<button id="button">Animate</button>

JavaScript:

document.getElementById("button").addEventListener("click", function () {
var circle = document.getElementById("circle");
var cx = 50 + Math.round(Math.random() * 300);
var cy = 50 + Math.round(Math.random() * 300);
// using 'setAttribute'
circle.setAttribute("cx", cx);
circle.setAttribute("cy", cy);

var rect = document.getElementById("rect");
var x = 50 + Math.round(Math.random() * 300);
var y = 50 + Math.round(Math.random() * 300);
// using 'setAttributeNS'
rect.setAttributeNS(null, "x", x);
rect.setAttributeNS(null, "y", y);
}, false);

CSS:

circle, rect {
-webkit-transition: all 0.7s ease-in-out;
-moz-transition: all 0.7s ease-in-out;
transition: all 0.7s ease-in-out;
}

这是一个完整的 JSFiddle:http://jsfiddle.net/kkhvzyjq/

在 Chrome 中,这工作得很好。然而,在 Safari 和 Firefox 中,虽然应用了新属性(形状移动),但没有过渡/动画。

有没有办法在这些浏览器中执行此操作?

最佳答案

Safari 和 Firefox 不会转换位置属性的变化。

CSS 属性 transform 对此效果更好:

http://jsfiddle.net/kkhvzyjq/7/

document.getElementById("button").addEventListener("click", function() {
var circle = document.getElementById("circle");
var cx = 50 + Math.round(Math.random() * 300);
var cy = 50 + Math.round(Math.random() * 300);
circle.style.transform = "translate(" + cx + "px," + cy + "px)";

var rect = document.getElementById("rect");
var x = 50 + Math.round(Math.random() * 300);
var y = 50 + Math.round(Math.random() * 300);
rect.style.transform = "translate(" + x + "px," + y + "px)";
}, false);
circle,
rect {
-webkit-transition: all 0.7s ease-in-out;
-moz-transition: all 0.7s ease-in-out;
transition: all 0.7s ease-in-out;
}
<svg width="400" height="400">
<circle id="circle" r="10" stroke="none" fill="blue" style="transform:translate(200px,200px);" />
<rect id="rect" height="10" width="10" stroke="none" fill="red" style="transform:translate(100px,100px);" />
</svg>
<button id="button">Animate</button>

关于javascript - 使用 CSS 过渡动画动态 SVG 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31005525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com