getting the width and height of SVG element after skew transformation - javascript

吃可爱长大的小学妹 提交于 2021-01-28 19:53:55

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!