[英]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.