在 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 选择器。