如何从使用转换动画的SVG元素中获取样式属性值?
如果我使用使用SMIL或CSS的转换动画的SVG元素,如何获得动画属性的计算样式?
在这里,我有一个旋转的< rect>
,但是您可以看到旋转
属性属性仅返回 none :
var rect1 = document.getElementById('rect1');
setTimeout(function(){
let rectStyle = getComputedStyle(rect1);
console.log(rectStyle.rotate);
}, 200);
<svg id="svg" width="200" viewBox="0 0 4 4" xmlns="http://www.w3.org/2000/svg">
<rect id="rect1" x="1" y="1" width="2" height="2" fill="red">
<animateTransform attributeName="transform"
attributeType="XML" type="rotate"
values="0 2 2; 360 2 2" dur="10s"
repeatCount="indefinite"/>
</rect>
</svg>
var rect1 = document.getElementById('rect1');
setTimeout(function(){
let rectStyle = getComputedStyle(rect1);
console.log(rectStyle.rotate);
}, 200);
#rect1 {
transform-origin: center;
animation-name: rotate;
animation-duration: 10s;
animation-timing-function: linear;
animation-iteration-count: infinite;
}
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
<svg id="svg" width="200" viewBox="0 0 4 4" xmlns="http://www.w3.org/2000/svg">
<rect id="rect1" x="1" y="1" width="2" height="2" fill="red" />
</svg>
If I have an SVG element that is animated using transform, either using SMIL or CSS, how do I get the computed style of the property that is animated?
Here I have a <rect>
that rotates, but as you can see the rotate
property just returns none
:
var rect1 = document.getElementById('rect1');
setTimeout(function(){
let rectStyle = getComputedStyle(rect1);
console.log(rectStyle.rotate);
}, 200);
<svg id="svg" width="200" viewBox="0 0 4 4" xmlns="http://www.w3.org/2000/svg">
<rect id="rect1" x="1" y="1" width="2" height="2" fill="red">
<animateTransform attributeName="transform"
attributeType="XML" type="rotate"
values="0 2 2; 360 2 2" dur="10s"
repeatCount="indefinite"/>
</rect>
</svg>
var rect1 = document.getElementById('rect1');
setTimeout(function(){
let rectStyle = getComputedStyle(rect1);
console.log(rectStyle.rotate);
}, 200);
#rect1 {
transform-origin: center;
animation-name: rotate;
animation-duration: 10s;
animation-timing-function: linear;
animation-iteration-count: infinite;
}
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
<svg id="svg" width="200" viewBox="0 0 4 4" xmlns="http://www.w3.org/2000/svg">
<rect id="rect1" x="1" y="1" width="2" height="2" fill="red" />
</svg>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在CSS动画的情况下,您可以使用
transform
而不是旋转
,但是您会得到类似matrix(....)
的东西。要获得确切的值,您需要类似于 a>。In the case of a CSS animation you can use
transform
instead ofrotate
but you get something likematrix(....)
. to get the exact value you need similar to this article .如果您愿意,只需阅读SMIL动画即可读取SMIL值。
In the case of a SMIL animation just read off the SMIL values if you want to.