簡體   English   中英

如何使用javascript給SVG文本元素提供固定的高度和寬度?

[英]How to give a fixed height and width to SVG text element using javascript?

我有多個不同高度和寬度的rect,我需要在rect的左上角顯示一個文本,無論文本的寬度是多少,都應將其調整為rect寬度的50%。

這是我嘗試過的代碼。

 rectBbox = rectElem.getBBox();
 textBbox = textElem.getBBox();
 scale = rectBbox.width / textBbox.width;
 X = parseFloat(rectBbox.x) 
 Y = parseFloat(rectBbox.y) 
 textElem.setAttribute("transform", "translate(" + X + "," + Y + ") scale(" + scale + ")");

在此處輸入圖片說明

我的svg看起來像

<svg>
<g id="maingroup">
<g id="firstchild">
<rect></rect>
<text></text>
</g>
<g id="nthchild">
<rect></rect>
<text></text>
</g>
<g>
</svg>

我如何縮放它,以便無論矩形或文本的大小是多少,文本都將在矩形寬度的50%內正確調整

在此示例中,我們將<text>元素放置在默認的0,0 然后,我們計算rect的左上方和文本的左上方之間的差異。

比例部分類似:0.5 *文本寬度與矩形寬度的比率。

 function adjustText(boxElem) { var rectElem = boxElem.querySelector("rect"); var textElem = boxElem.querySelector("text"); var rectBbox = rectElem.getBBox(); var textBbox = textElem.getBBox(); var scale = 0.5 * rectBbox.width / textBbox.width; var translateX = rectBbox.x - textBbox.x; var translateY = rectBbox.y - textBbox.y; textElem.setAttribute("transform", "translate(" + translateX + "," + translateY + ") scale(" + scale + ")"); } adjustText(document.getElementById("firstchild")); adjustText(document.getElementById("nthchild")); 
 <svg width="500" height="500"> <g id="maingroup"> <g id="firstchild"> <rect x="20" y="30" width="250" height="100" fill="lightgrey" stroke="black"/> <text>Very Very Very Very Very Long Text</text> </g> <g id="nthchild"> <rect x="200" y="200" width="200" height="100" fill="lightgrey" stroke="black"/> <text>Smaller Text</text> </g> </g> </svg> 

首先,我需要計算文本的寬度( txtlength )和框的寬度( w )。 我想縮放文本,所以我要計算縮放比例, let thescale = w / (2*txtlength); //這會將文字縮放為矩形寬度的50%。 接下來,使用setAttributeNS設置transform屬性的值。 請注意,文本沒有以SVG畫布的原點為中心的x和y屬性。

 let txtlength = txt.getComputedTextLength() let w = theRect.getBBox().width; let c = {x:50,y:25}// the center of the rect let thescale = w / (2 * txtlength);// 50% of rect's width //scale the text and translate in the center txt.setAttributeNS(null, "transform", `scale(${thescale},${thescale}) translate(${cx/thescale},${cy/thescale})`) 
 svg{border:1px solid; width:120vh} text{font-size:10; dominant-baseline: middle; text-anchor: middle} 
 <svg viewBox="0 0 100 50"> <rect id="theRect" x="10" y="10" width="80" height ="30" stroke="black" fill="none" /> <text id="txt" dominant-baseline="middle" text-anchor="middle">A very long text, sooo long </text> </svg> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM