簡體   English   中英

如何在 SVG 區域中居中文本

[英]How to center text in an SVG region

我試圖在我的 SVG 區域中將文本居中,但沒有成功。 有沒有人對如何優化這個有任何見解?

 <svg xmlns="http://www.w3.org/2000/svg" aria-label="Usa Mo" viewBox="0 0 70.389999 62.16"> <g> <path tabindex="0" aria-label="Sainte Genevieve" fill="red" id="sainte genevieve" name="Sainte Genevieve" d="m 57.466419,33.749401 2.854,2.605 -1.578,2.754 -0.463,-0.343 -0.441,0.418 -1.953,-1.762 -0.824,-0.796 1.293,-1.417 -0.982,-0.73 1.582,-1.112 0.512,0.383" > </path> <text font-family="Verdana" font-size="0.75" fill="blue"> <textPath href="#sainte genevieve" startOffset="50%" text-anchor="middle">Sainte Genevieve</textPath> </text> </g> </svg>

OP正在評論:

我只希望文本位於彩色區域內並且正面朝上。

在這種情況下,您不需要使用 textPath。 您需要找到路徑的中心。 為此,您首先獲得路徑的邊界框: let bb = thePath.getBBox()

接下來,您將獲得路徑的中心:

let x = bb.x + bb.width/2;
let y = bb.y + bb.height/2;

最后,您將文本的 x 和 y 屬性設置為 x 和 y,從而確保文本以該點為中心: text-anchor="middle" dominant-baseline="middle"

 let bb = thePath.getBBox(); theText.setAttribute("x", bb.x + bb.width/2); theText.setAttribute("y", bb.y + bb.height/2);
 svg{border:1px solid; width:300px}
 <svg xmlns="http://www.w3.org/2000/svg" aria-label="Usa Mo" viewBox="50 30 15 12"> <path id="thePath" aria-label="Sainte Genevieve" fill="red" id="sainte_genevieve" name="Sainte Genevieve" d="m 57.466419,33.749401 2.854,2.605 -1.578,2.754 -0.463,-0.343 -0.441,0.418 -1.953,-1.762 -0.824,-0.796 1.293,-1.417 -0.982,-0.73 1.582,-1.112 0.512,0.383" > </path> <text id="theText" font-family="Verdana" font-size=".75" fill="blue" text-anchor="middle" dominant-baseline="middle"> Sainte Genevieve </text> </svg>

觀察:我改變了 svg 元素的 viewBox,因為我想讓路徑在中心。 你可以把它改回原來的樣子。

暫無
暫無

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

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