问题
I have an SVG rect
with the following atributes:
<rect x="50" y="10" width="20" height="30" style="stroke: #000000; fill:none;" />
If I apply a skewX(10)
tranformation, the width and height of the rectangle change. How do I then calculate its true width and height using plain javascript (without libraries)?
回答1:
Wrap the <rect>
in a <g>
element; then get a reference to the group; then call getBBox()
on it.
var bbox = document.getElementById("wrapper").getBBox();;
alert("width=" + bbox.width + " height=" + bbox.height);
<svg>
<g id="wrapper">
<rect x="50" y="10" width="20" height="30" style="stroke: #000000; fill:none;"
transform="skewX(10)" />
</g>
</svg>
The reason we wrap the element in a group is because the bounding box returned by getBBox()
does not include the effects of the transform. Also, it doesn't have to be a <g>
it could be any parent of the <rect>
, as long as there are no other child elements that could affect the bounds.
Or you could use trigonometry like Stephen suggests.
来源:https://stackoverflow.com/questions/28051819/getting-the-width-and-height-of-svg-element-after-skew-transformation-javascri