在 SVG 中使用字型

SVG 支援多種為 <text> 元素指定字型的方式。推薦的現代方法是使用 CSS,這與您在 HTML 中設定字型樣式的方式基本相同。

使用 CSS 應用和設定字型樣式

下面的程式碼展示瞭如何使用 CSS 為給定的 <text> 元素設定特定字型樣式:在本例中是系統字型“Courier New”。請注意,這裡的 CSS 巢狀在 SVG 的 <style> 元素中,但也可以在包含的 HTML 中應用。

html
<svg>
  <style>
    text {
      /* Specify the system or custom font to use */
      font-family: "Courier New", monospace;

      /* Add other styling */
      font-size: 24px;
      font-weight: bold;
      font-style: italic;
    }
  </style>
  <text x="10" y="20">Some text</text>
</svg>

渲染效果如下所示

使用 @font-face 引入 Web 字型

上一節使用 CSS 應用了系統字型,但您也可以使用 @font-face at-rule 指定的 Web 字型,以完全相同的方式應用。

示例演示瞭如何先定義然後使用一個名為“FiraSans”的字體系列

html
<svg
  viewBox="0 0 400 50"
  width="350"
  height="50"
  xmlns="http://www.w3.org/2000/svg">
  <style>
    /* Define the font family using web fonts */
    @font-face {
      font-family: "FiraSans";
      src:
        url("https://mdn.github.io/shared-assets/fonts/FiraSans-Italic.woff2")
          format("woff2"),
        url("https://mdn.github.io/shared-assets/fonts/FiraSans-Bold.woff2")
          format("woff2");
    }

    /* Style the text */
    text {
      /* Specify the system or custom font to use */
      font-family: "FiraSans", sans-serif;

      /* Add other styling */
      font-size: 24px;
      font-weight: bold;
      font-style: italic;
    }
  </style>
  <text x="10" y="20">Text styled with custom font</text>
</svg>

在 text 元素中引用樣式

您還可以使用 font-family 屬性直接在 <text> 元素中引用樣式。這段程式碼展示瞭如何將自定義字型“My Font”應用到 <text> 元素。

svg
<svg>
  <text font-family="My Font" x="10" y="20">Text using "My Font" font</text>
</svg>

請注意,這類似於為 HTML 元素應用樣式。雖然在某些情況下可能有用,但通常最好使用 CSS 和 CSS 選擇器。