如何获得 SVG 文本元素的紧密边界框 [英] How get tight bounding box of an SVG Text Element

查看:40
本文介绍了如何获得 SVG 文本元素的紧密边界框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常为了获得 SVG 中任何元素的边界框,我们使用 getBoundingClientRect() 或 getBBox() 分别为我们提供顶部、底部、左侧、右侧、宽度、高度或 x、y、宽度、高度.但是当文本旋转时,这些值不足以使元素的边界框紧密,因为由这些值形成的框将具有水平和垂直边缘,不平行于文本.如何为旋转文本选择紧密边界框,如下图所示.(该文本由 Chrome Inspect Element Selector 突出显示.)

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

推荐答案

我想如果你想要 4 个点,你可能需要在边界框上用与元素相同的变换来变换它们.如果只是为了显示,只需将相同的变换应用于已显示的边界框.我觉得如果你要4分的话,就稍微复杂一点,不过可能有更简单的方法.

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.

var text = document.querySelector('text');
var svg = document.querySelector('svg')


function getTransformedPts( el ) {
  var m = el.getCTM();
  var bb = el.getBBox();
  var tpts = [
    matrixXY(m,bb.x,bb.y),
    matrixXY(m,bb.x+bb.width,bb.y),
    matrixXY(m,bb.x+bb.width,bb.y+bb.height),
    matrixXY(m,bb.x,bb.y+bb.height) ]
  
  return tpts;
}

function matrixXY(m,x,y) {
            return { x: x * m.a + y * m.c + m.e, y: x * m.b + y * m.d + m.f };
}

var pts = getTransformedPts( text );

for( pt in pts ) {
  var c = document.createElementNS("http://www.w3.org/2000/svg","circle");
  c.setAttribute('cx', pts[pt].x);
  c.setAttribute('cy', pts[pt].y);
  c.setAttribute('r',3)
  svg.append(c)
}

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="800" height="800">
<text x="50" y="50" transform="rotate(10)" font-size="30">testing rotated text box points</text>
</svg>

这篇关于如何获得 SVG 文本元素的紧密边界框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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