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