I am working on svg.
<div id="wrap" style="transform: scale(2); width:300;height:300;">
<svg id="real" style="border:red 10px solid;" >
<rect/>
</svg>
</div>
var e = document.getElementById("real");
//an api to get scale from e directly ??
My question is, how get the scale of this svgElement?
I tried e.getCTM()
and e.getScreen()
. The matrix does not contain the scale information.
Please give me some advice.
This is not possible, or better put the `real element is not being transformed. If it were to inherit the tranformation, it would be scaled twice effectively.
You would be looking for
getComputedStyle
, but it'll tell you the same. For reference, a property that is inherited is included here:Another SO answer shows how to get the scale of an element relative to the document using
element.getBoundingClientRect().width / element.offsetWidth
. However, thesvg
element does not have theoffsetWidth
property. Therefore, one solution is to temporarily prepend a "offsetWidth-able" element to thesvg
element, e.g. adiv
, read the ratio on this temporary helper, and then delete it. On the off chance that the inserted element will have an unexpected scale transform applied to it through CSS (as shown in the code snippet), this inserted element should have a style oftransform: scale(1);
applied to it directly.Update: A further complication arises when a CSS transform including a scale is applied directly to the
svg
element itself. In this case, parsing of the style is required which can be accomplished usinggetComputedStyle
andgetPropertyValue
, and extracting the scale value from the returned matrix string. This then needs to be multiplied by the relative scale of the prependeddiv
.Further Update: This solution does not appear to currently work in Safari because the browser is not recognizing
insertAdjacentHTML
in spite of the fact that the documentation I can find says it should. (Is this a Safari bug or am I missing something?) However, the solution does work in Firefox and Chrome.When you run the code snippet above, you may have to scroll down in the snippet window or click on "Full page" to see the results.