如何获取使用transform实现动画的SVG元素的样式属性值
问题原因
直接通过getComputedStyle读取rotate属性拿到none,核心是两个原因:
- CSS动画如果是作用在
transform复合属性上,并不会修改独立CSS属性rotate的值。独立的rotate/scale/translate是后期新增的CSS属性,和transform属性值里的rotate()等变换函数不是同一个东西,没给它赋值的话它永远返回默认值none。 - SMIL的
animateTransform是直接修改SVG元素XML层面的transform属性,不属于CSS样式规则范畴,getComputedStyle只会读取CSSOM层面的计算样式,捕获不到SMIL动画产生的实时属性变化。
通用解决方案
不管是CSS动画还是SMIL动画驱动的SVG变换,最通用、兼容性最好的获取实时变换状态的方法是使用SVG原生的getCTM()方法,它会返回元素当前应用了所有变换(包括动画产生的实时变换)之后,相对于最近SVG视口的变换矩阵:
const rect = document.getElementById('rect1'); setTimeout(() => { // 获取当前实时变换矩阵 const transformMatrix = rect.getCTM(); // 从矩阵中反推当前旋转角度 const rotateAngle = Math.round(Math.atan2(transformMatrix.b, transformMatrix.a) * (180 / Math.PI)); console.log('当前旋转角度:', rotateAngle); }, 200);
CSS动画场景的补充方法
如果确定变换动画是纯CSS实现的,也可以直接读取getComputedStyle返回的transform字段,它会返回当前动画帧下的CSS变换矩阵:
const rect = document.getElementById('rect1'); setTimeout(() => { const computedStyle = getComputedStyle(rect); // 拿到CSS层的实时transform矩阵 const matrix = new DOMMatrix(computedStyle.transform); const rotateAngle = Math.round(Math.atan2(matrix.b, matrix.a) * (180 / Math.PI)); console.log('CSS动画下当前旋转角度:', rotateAngle); }, 200);
注意:这个方法对SMIL动画无效,SMIL修改的XML属性不会同步到CSSOM的transform值上。
内容的提问来源于stack exchange,提问作者chrwahl
相关产品推荐
相关产品推荐

