我正在嘗試根據某些形狀將文本居中放置。
在下面的示例中,每個正方形的高度和寬度都是 SVG 的 50%。我試圖將非常大的“X”字符居中。直覺上,我想將文本的 x 和 y 設定為任何正方形的中心(25%,25% 或 25%,75% 或 75%,75% 或 75%,25%),但它關閉了。我需要稍微調整百分比以將它們居中。
在下面的示例中,看起來我的直覺在左上角的正方形中是錯誤的,而將 y% 稍微調整為在右上角的正方形中。包含較小的藍色和綠色方塊以準確顯示 25%,25% 和 25%,75% 的位置。
我注意到當字體大小改變時,這也會改變。有沒有辦法根據字體大小使用百分比來居中文本?為了理解為什么這不起作用,我缺少什么關鍵概念?
<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 200 200">
<style>
.f{font-family:monospace;font-size:80pt}
</style>
<rect width="50%" height="50%" y="0%" fill="red"/>
<rect width="50%" height="50%" y="50%" fill="green"/>
<rect width="50%" height="50%" y="0%" x="50%" fill="yellow"/>
<rect width="50%" height="50%" y="50%" x="50%" fill="blue"/>
<text x="25%" y="25%" class="f" dominant-baseline="middle" text-anchor="middle">X</text>
<text x="75%" y="29%" class="f" dominant-baseline="middle" text-anchor="middle" fill="blue">X</text>
<rect width="25%" height="25%" y="25%" x="25%" fill="blue"/>
<rect width="25%" height="25%" y="25%" x="75%" fill="green"/>
</svg>

uj5u.com熱心網友回復:
看起來你想要dominant-baseline="central" 而不是中間。
<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 200 200">
<style>
.f{font-family:monospace;font-size:80pt}
</style>
<rect width="50%" height="50%" y="0%" fill="red"/>
<rect width="50%" height="50%" y="50%" fill="green"/>
<rect width="50%" height="50%" y="0%" x="50%" fill="yellow"/>
<rect width="50%" height="50%" y="50%" x="50%" fill="blue"/>
<text x="25%" y="25%" class="f" dominant-baseline="central" text-anchor="middle">X</text>
<text x="75%" y="29%" class="f" dominant-baseline="central" text-anchor="middle" fill="blue">X</text>
<rect width="25%" height="25%" y="25%" x="25%" fill="blue"/>
<rect width="25%" height="25%" y="25%" x="75%" fill="green"/>
</svg>
uj5u.com熱心網友回復:
該字體允許顯示所有字符。
你需要改變基線
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/alignment-baseline
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/dominant-baseline
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/baseline-shift
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/312324.html
標籤:svg
