How to get svgElement scale?
I am working on svg.
<divid="wrap"style="transform: scale(2); width:300;height:300;"><svgid="real"style="border:red 10px solid;"><rect/></svg></div>vare =document.getElementById("real");//an api to get scale from e directly ??My question is: how to get the scale of this svgElement?
I triede.getCTM()ande.getScreen().The matrix does not contain scale information.
Please give me some advice.
+2
2answers
SO, ,element.getBoundingClientRect().width / element.offsetWidth.svgoffsetWidth. "offsetWidth-able"svg, . adiv, . , , CSS ( ),transform: scale(1);.
. , CSS-, ,svg. ,getComputedStylegetPropertyValue, .div.
. Safari,insertAdjacentHTML, , , , , . ( Safari - ?) Firefox Chrome.
vare =document.getElementById("real");varcomputedTransform =window.getComputedStyle(e).getPropertyValue("transform");if(computedTransform ==="none") {eDirScale =1;}else{varmatrix = computedTransform.match(/matrix\(([^\)]*)\)/)[1].split(/, *| +/);varscaleX =Math.sqrt(matrix[0] * matrix[0] + matrix[1] * matrix[1]);varscaleY =Math.sqrt(matrix[2] * matrix[2] + matrix[3] * matrix[3]);if(scaleX !== scaleY)throw"non-uniform scaling";eDirScale = scaleX;}vareRelScale = e.getBoundingClientRect().width / e.offsetWidth;e.insertAdjacentHTML('beforebegin','<div id="temporaryPrepended" style="transform: scale(1)"></div>');varprepended =document.getElementById("temporaryPrepended");varpRelScale = prepended.getBoundingClientRect().width / prepended.offsetWidth;prepended.parentNode.removeChild(prepended);varscale = pRelScale * eDirScale;document.write("<p>scale directly on 'svg': "+ eDirScale +"</p>");document.write("<p>scale on 'svg' relative to document: "+ eRelScale +", i.e. doesn't work in e.g. Firefox and, while it might work in Chrome (in Feb 2016), apparently won't in the near future</p>");document.write("<p>scale on prepended 'div' relative to document: "+ pRelScale +"</p>");document.write("<p>total scale on 'svg' relative to document: "+ scale +"</p>");div{transform:scale(4);}<divid="wrap"style="transform: scale(2); width:300;height:300;"><svgid="real"style="transform: translate(10px, 10px) scale(1.5); border:red 10px solid; opacity: 0.3;"><rect/></svg></div>, " ", .
+2
, " " . , .
getComputedStyle, . , , , :
vare =document.getElementById("real");console.log(window.getComputedStyle(e)["transform"]);console.log(window.getComputedStyle(e)["color"]);<divid="wrap"style="transform: scale(2); color: blue; width:300; height:300;"><svgid="real"style="border: red 10px solid;"><rect/></svg></div>0