javascript - 如果svg <text>的高度和宽度大于javascript中svg <rect>的高度和宽度,如何更改它?

标签 javascript svg

    <g id="newGroup" >
        <rect class="newClass" id="svg_106"  x="133.2" y="384.5" width="76.2" height="38.1" />
        <text class="newText" id="svg_110" style="pointer-events: inherit;" transform="matrix(0.7912 0 0 1 111.325 414.395)" x="31.5976" y="-12">This is a very long text text text text text</text>
    </g>

我想调整矩形内的文本。有些文本的宽度大于矩形本身的宽度。我想调整文本,使其正确适合矩形内。

最佳答案

transform关于<text> element 使事情变得有点复杂。

我要做的是删除变换,然后测量文本的大小。然后您可以给它一个新的变换,适本地缩放它并将其放置在正确的位置。

adjustText("svg_106", "svg_110");


function adjustText(rectId, textId)
{
  var rectElem = document.getElementById(rectId);
  var textElem = document.getElementById(textId);
  // Get the rectangle bounds
  var rectBBox = rectElem.getBBox();
  // Clear the text position and transform so we can measure the text bounds properly
  textElem.setAttribute("x", "0");
  textElem.setAttribute("y", "0");
  textElem.removeAttribute("transform");
  var textBBox = textElem.getBBox();
  // Calculate an adjusted position and scale for the text
  var padding = 5;  // How much horizontal padding between the text and the rectangle sides
  var scale = (rectBBox.width - 2 * padding) / textBBox.width;
  var textX = rectBBox.x + padding;
  var textY = rectBBox.y + (rectBBox.height / 2) - scale * (textBBox.y + textBBox.height / 2);
  // Add a new transform attribute to the text to position it in the new place with the new scale
  textElem.setAttribute("transform", "translate("+textX+","+textY+") scale("+scale+")");
}
.newClass {
  fill: grey;
}
<svg viewBox="0 300 500 200">
  <g id="newGroup" >
    <rect class="newClass" id="svg_106"  x="133.2" y="384.5" width="76.2" height="38.1" />
    <text class="newText" id="svg_110" style="pointer-events: inherit;" transform="matrix(0.7912 0 0 1 111.325 414.395)" x="31.5976" y="-12">This is a very long text text text text text</text>
  </g>
</svg>

关于javascript - 如果svg <text>的高度和宽度大于javascript中svg <rect>的高度和宽度,如何更改它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53246789/

相关文章:

javascript - 如何将 json 数据传递到 .js 文件

javascript - 分配给 {}.toString 是什么意思?

javascript - 在 HTML 中使用多种表单

html - 如何让 SVG 中的 <image> 改变颜色?

svg - 如何使用 D3.js 在 SVG 中创建流布局?

javascript - SVG - getElementsByClassName

css - SVG 动画标志

JavaScript - 如何在 Firefox 浏览器中启用箭头键,同时根据特殊字符验证输入字段

javascript - Onclick 不与按钮重复(变量最大值为整数 1)

javascript - 如何从一个 SVG 元素中的点绘制到另一个 SVG 元素中的点?