在倾斜变换后获取SVG元素的宽度和高度 - javascript [英] getting the width and height of SVG element after skew transformation - javascript

查看:26
本文介绍了在倾斜变换后获取SVG元素的宽度和高度 - javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下属性的 SVG rect:

I have an SVG rect with the following atributes:

<rect x="50" y="10" width="20" height="30" style="stroke: #000000; fill:none;"  />

如果我应用 skewX(10) 转换,矩形的宽度和高度会发生变化.然后我如何使用普通的 javascript(没有库)计算它的真实宽度和高度?

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)?

推荐答案

包裹在 元素中;然后获得对该组的引用;然后在其上调用 getBBox().

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>

我们将元素包装在一个组中的原因是因为 getBBox() 返回的边界框不包括变换的效果.此外,它不必是 它可以是 的任何父元素,只要没有其他子元素可能会影响边界.

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.

这篇关于在倾斜变换后获取SVG元素的宽度和高度 - javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆