Usually in order to get bounding box of any element in SVG we use getBoundingClientRect() or getBBox() which gives us top, bottom, left, right, width, height or x, y, width, height respectively. But when the text is rotated these values are not enough to get tight bounding box of the element as box formed by these values will have horizontal and vertical edges, not parallel to the text. How can the tight bounding box be selected for a rotated text as shown in the image below. (The text was highlighted by Chrome Inspect Element Selector.)
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
There is no direct method to achieve this. But you can try the below solution.
How to get rotated svg text bounds in javascript programmatically
If you are getting the bounding box of a
<text>
element usinggetBBox()
, then it normally is the unrotated bounding box. That's becausegetBBox()
does not include the elementstransform
when calculating the value to return.For example, have a look at the example below. Compare the text BBox and the BBox of its parent group element.
I think if you want the 4 points, you may have to transform them on the bounding box with the same transform as the element. If it's just for display, just apply the same transform to a bounding box that has been displayed. I think if you want the 4 points, it's a bit more complicated, but there may be a simpler way.
This may be useful anyway.
We grab the bounding box of the text. We grab the matrix (in this case rotation) on the element. Then we apply that to all the points we gather from the bounding box. I've added a bit more code, just to create circles at the points, to highlight it.