SVG 強大之處之一,是它把文本控制精度做到了普通 HTML 頁面難以企及的程度,而且不需要依賴圖片或插件。凡是能施加在圖形與路徑上的操作——描邊、填充、濾鏡——同樣可以用在文字上。
不過它有一個明顯短板:SVG 不會自動換行。文本超出可用空間時會直接被切斷,要多行顯示通常得寫多個 text 元素,或者手動控制 y 座標。另外,text 元素內的空白處理方式和 HTML 類似:換行與回車折算成空格,連續空格壓縮成一個。
<svg> <rect width="300" height="200" fill="red" /> <circle cx="150" cy="100" r="80" fill="green" /> <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">SVG</text> </svg>
常用屬性:
start(錨點在開頭,文本向右排)、middle(居中向兩側排)、end(錨點在結尾,文本向左排)以下屬性既可寫在 CSS 裡,也可直接作為呈現屬性:fill、stroke,以及 font-family、font-style、font-weight、font-variant、font-stretch、font-size、font-size-adjust、kerning、letter-spacing、word-spacing、text-decoration 這一整組字體相關屬性。
tspan 是 text 的得力補充,用於渲染其中一段文本,只能作為 text 或 tspan 的子元素出現。最典型的用途就是局部強調。
<text> <tspan font-weight="bold" fill="red">This is bold and red</tspan> </text>
可用屬性:
<text x="10" y="10">Hello World! <tspan x="100 200 300" font-weight="bold" fill="red">This is bold and red</tspan> </text>
<text x="10" y="10">Hello World! <tspan rotate="10 20 45" font-weight="bold" fill="red">This is bold and red</tspan> </text>
tref 可以引用一處已定義的文本並複製到當前位置,通常配合 xlink:href 指向目標元素。因為是複製而非引用,用 CSS 改當前文本不會影響原文。
<text id="example">This is an example text.</text> <text> <tref xlink:href="#example" /> </text>
需要提醒的是,tref 在 SVG 2 中已被移除,新專案不建議再使用。
這個元素效果很出彩,能做出不少藝術字效果。它會抓取 xlink:href 指定路徑,把文本對齊到該路徑上。
<path id="my_path" d="M 20,20 C 40,40 80,40 100,20" /> <text> <textPath xlink:href="#my_path">This text follows a curve.</textPath> </text>
SVG 的 image 元素可以直接顯示點陣圖,用法很簡單。
<svg width="5cm" height="4cm"> <image xlink:href="Penguins.jpg" x="0" y="0" height="50px" width="50px"/> </svg>
幾個容易忽略的細節: