javascript - 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.
解决方案
transform
on元素使<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>
推荐阅读
- javascript - Mapbox 标记弹出窗口不会单独打开/关闭
- javascript - 从模态输入中获取数据,计算然后在模态中显示结果
- maven - maven-pmd-plugin 未识别错误
- python - 无法将元组列表转换为字典
- javascript - 在设置处理程序之前调用事件处理程序
- javascript - 节点 js 未在 MySql 数据库中保存数据
- azure - 无法在 Azure App 服务上部署 IdentityServer 4 代码
- python - 如何关闭使用变量资源管理器打开的所有数据框?
- r - 如何从每一行中删除 NA
- javascript - 替换子字符串 javascript