繁体   English   中英

如何从使用变换动画的 SVG 元素中获取样式属性值?

[英]How do I get a style property value from an SVG element that is animated using transform?

如果我有一个使用变换动画的 SVG 元素,使用 SMIL 或 CSS,我如何获得动画属性的计算样式?

这里我有一个可以旋转的<rect> ,但是你可以看到rotate属性只返回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>

在 CSS 动画的情况下,您可以使用transform而不是rotate ,但您会得到类似matrix(....)的东西。 要获得类似于本文所需的确切值。

 var rect1 = document.getElementById('rect1'); setTimeout(function(){ let rectStyle = getComputedStyle(rect1); let values = rectStyle.transform.split('(')[1]; values = values.split(')')[0]; values = values.split(','); let a = values[0]; let b = values[1]; let c = values[2]; let d = values[3]; var angle = Math.atan2(b, a) * (180/Math.PI); console.log(angle); }, 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>

在 SMIL 动画的情况下,如果您愿意,只需读取 SMIL 值。

 var rect1 = document.getElementById('rect1'); setTimeout(function(){ let a = rect1.transform.animVal[0].matrix.a; let b = rect1.transform.animVal[0].matrix.b; let angle = Math.atan2(b, a) * (180/Math.PI); console.log(angle); }, 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM