在没有外部文件的情况下在svg中使用FontAwesome图标

时间:2013-08-14 07:46:49

标签: css svg include icons font-awesome

我需要创建一个SVG(使用PHP和/或Javascript),其中一些SVG元素是来自FontAwesome的图标,但是:没有外部依赖(例如:导入css文件等)。

我发现了this stackoverflow问题,这是一个类似的话题,但不适合我的问题,因为有外部依赖,比如在显示svg的网页上添加FontAwesome(CSS文件)。

不同的是,我需要一个一体化的SVG,其中所有必需的FontAwesome定义都是svg的一部分,因为用户应该能够下载生成的SVG以继续使用svg查看器进行处理或编辑。

有没有办法,将(例如)一个“Font Awesome”图标的定义放入一个svg?

我找到了this(可能)svg信息列表。所以看起来,图标路径可用作SVG代码。那么我可以在svg中使用它吗?


//更新:我找到了以下示例,但我不知道,如何包含FontAwesome定义以及如何访问图标: - (

<?xml version="1.0" standalone="yes"?>
<svg width="100%" height="100%" version="1.1"
 xmlns = 'http://www.w3.org/2000/svg'>
  <defs>
    <font id="Font2" horiz-adv-x="1000">
      <font-face font-family="Super Sans" font-weight="normal" font-style="italic"
          units-per-em="1000" cap-height="600" x-height="400"
          ascent="700" descent="300"
          alphabetic="0" mathematical="350" ideographic="400" hanging="500">
        <font-face-src>
          <font-face-name name="Super Sans Italic"/>
        </font-face-src>
      </font-face>
      <missing-glyph><path d="M0,0h200v200h-200z"/></missing-glyph>
      <glyph unicode="!" horiz-adv-x="300"><!-- Outline of exclam. pt. glyph --></glyph>
      <glyph unicode="@"><!-- Outline of @ glyph --></glyph>
      <!-- more glyphs -->
    </font>
  </defs>
</svg>

1 个答案:

答案 0 :(得分:14)

您的示例是SVG字体,它不适用于IE或Firefox。您需要将FontAwesome编码为数据URI并嵌入@font-face,如果您希望它可以在任何地方工作:

<svg width="500" height="200" version="1.1" xmlns = 'http://www.w3.org/2000/svg' xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 500 200">  
    <defs>
      <style type="text/css">
        @font-face {
          font-family: 'FontAwesome';
          src: url(data:font/opentype;base64,[...]) format('opentype');
        }
      </style>
    </defs>
    <rect x="0" y="0" height="100" width="500" fill="#eee" />
    <text x="20" y="50" font-family="FontAwesome" font-weight="normal" font-size="32">
      &#xf007
    </text>
  </svg>

[...]替换为字体的base64编码版本。您可以将.ttf或.otf文件上载到base64服务或命令行openssl base64 -in <infile> -out <outfile>

如果要对FontAwesome的库进行子集化,可以前往icomoon http://icomoon.io/app/#library并添加FontAwesome库。然后选择所需的图标,下载zip,然后将ttf上传到base64编码服务,例如http://www.opinionatedgeek.com/dotnet/tools/base64encode/,并将生成的字符串粘贴到src: font-face声明中。