首页 > 解决方案 > How to change the height and width of svg ,if it is greater than the height and width of svg in javascript?

问题描述

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

I want to adjust the text inside a rect.Some text are greater in width than the width of rect itself.I want to adjust the text so that it properly fits inside the rect.

标签: javascriptsvg

解决方案


transformon元素使<text>事情变得有点复杂。

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

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>


推荐阅读