文字
當談論 SVG 中的文字時,我們必須區分兩個幾乎完全獨立的主題。一個是影像中文字的包含和顯示,另一個是 SVG 字型。後者將在教程的後續部分中介紹,而本頁將重點關注第一部分:將文字引入 SVG 影像。
基礎知識
我們在 入門示例 中已經看到,text 元素可用於在 SVG 文件中放置任意文字。
xml
<text x="10" y="10">Hello World!</text>
x 和 y 屬性決定文字在視口中的位置。text-anchor 屬性,其值可以是 "start"、"middle"、"end" 或 "inherit",決定了文字從該點流動的方向。dominant-baseline 屬性決定了垂直對齊方式。
與形狀元素一樣,文字可以使用 fill 屬性著色,並使用 stroke 屬性描邊。兩者都可以引用漸變或圖案,這使得 SVG 中的文字著色非常強大。
設定字型屬性
文字的一個重要部分是顯示它的字型。SVG 提供了一組屬性,其中許多與其 CSS 對應項相似,用於啟用字型選擇。以下每個屬性都可以作為屬性設定,或透過 CSS 宣告設定:font-family、font-style、font-weight、font-variant、font-stretch、font-size、font-size-adjust、letter-spacing、word-spacing 和 text-decoration。
其他與文字相關的元素
tspan
此元素用於標記較大文字的子部分。它必須是 text 元素或另一個 tspan 元素的子元素。一個典型的用例是將句子中的一個單詞顯示為粗體紅色。
html
<svg width="350" height="60" xmlns="http://www.w3.org/2000/svg">
<text>
This is
<tspan font-weight="bold" fill="red">bold and red</tspan>
</text>
<style>
<![CDATA[
text {
dominant-baseline: hanging;
font: 28px Verdana, Helvetica, Arial, sans-serif;
}
]]>
</style>
</svg>
tspan 元素具有以下自定義屬性
textPath
此元素透過其 href 屬性獲取任意路徑,並沿著該路徑排列其所包含的字元。
html
<svg width="200" height="100" xmlns="http://www.w3.org/2000/svg">
<path id="my_path" d="M 20,20 C 80,60 100,40 120,20" fill="transparent" />
<text>
<textPath xmlns:xlink="http://www.w3.org/1999/xlink" href="#my_path">
A curve.
</textPath>
</text>
<style>
<![CDATA[
text {
dominant-baseline: hanging;
font: 28px Verdana, Helvetica, Arial, sans-serif;
}
]]>
</style>
</svg>