自定义字体不显示在用作背景图像的SVG图案中

Fab*_*ert 7 html css firefox svg background-image

我正在使用使用自定义字体的SVG模式,以便将该模式用作 HTML页面上的背景图像.

在Chrome和Safari中,一切都很好,但它在Firefox中开始变得有趣:

  • 当我打开SVG文件本身时,Firefox就会将SVG和自定义字体文本一起渲染(到目前为止一直很好!);
  • 不过,Firefox也不要再渲染自定义字体时相同的SVG文件作为背景,以一个HTML元素(!)

我花了好几个小时试图孤立这个问题,欢迎一双新鲜的眼睛.

单击此处查看问题的最小演示.

这就是我的简要内容:

CSS:

@import url(http://fonts.googleapis.com/css?family=Indie+Flower);

body {
    background: url(pattern-google.svg);
}
Run Code Online (Sandbox Code Playgroud)

SVG文件:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" height="200" width="200">
    <style type="text/css">@import url(http://fonts.googleapis.com/css?family=Indie+Flower);</style>
    <defs>
        <!-- Geometry -->
        <g>
            <rect id="square" x="0" y="0" width="200" height="200" />
        </g>

        <!-- Patterns with Text -->
        <pattern id="pattern" x="0" y="0" width="40" height="40" patternUnits="userSpaceOnUse" text-anchor="middle" font-size="20" font-family="Indie Flower, sans-serif" style="font-family: Indie Flower, sans-serif;">
            <rect x="00" y="00" width="40" height="40" fill="transparent" />
            <text x="00" y="00" fill="#777">S</text>
            <text x="40" y="00" fill="#777">S</text>
            <text x="20" y="20" fill="#777">S</text>
            <text x="00" y="40" fill="#777">S</text>
            <text x="40" y="40" fill="#777">S</text>
        </pattern>
    </defs>

    <!-- Graphics -->
    <use xlink:href="#square" transform="translate(0, 0)" fill="url(#pattern)"/>
</svg>
Run Code Online (Sandbox Code Playgroud)

HTML本身并不重要,但我在下面链接了它.我最终没有生成一个jsfiddle,因为我无法在那里托管SVG文件.

(在演示之外,这里的真实应用是我想使用自定义字体来显示拼音符号.(作为背景图片,帮助人们学习它们.)在SVG中这样做可以省去导出到位图的麻烦我随时改变设计.)

谢谢您的帮助.

Rob*_*son 10

您正在图像上下文中使用SVG.即通过html <img>标签,SVG <image>标签或在您的情况下作为背景图像.

在Firefox中(在某些时候可能在其他UA中)图像必须仅包含单个文件.图像文件外部的任何数据(pattern-google.svg)都将被忽略.如果直接显示SVG,则加载/使用外部数据.

所以,你可以做什么...

将数据作为数据URI加载.即base64编码http://fonts.googleapis.com/css?family=Indie+Flower, 但在执行此操作之前阅读最后一段,然后将该数据直接粘贴到svg文件本身.

所以导入看起来像这样......

@import url('data:text/css;base64,whatever the base 64 encoded data looks like...')
Run Code Online (Sandbox Code Playgroud)

请注意,因为http://fonts.googleapis.com/css?family=Indie+Flower本身具有外部数据,因此数据本身必须自身编码为数据URI.即你必须一直沿着兔子洞走.并在下面勾画出来更改该文件.

@font-face {
  font-family: 'Indie Flower';
  font-style: normal;
  font-weight: 400;
  src: local('Indie Flower'), local('IndieFlower'), url(**convert this file to a data URI too before you convert the whole file to a data URI**) format('woff');
}
Run Code Online (Sandbox Code Playgroud)

完成后,您可以将整个文件编码为数据URI并@import它.

所以,一步一步地重申......

  1. 转换http://themes.googleusercontent.com/static/fonts/indieflower/v5/10JVD_humAd5zP2yrFqw6nhCUOGz7vYGh680lGh-uXM.woff到数据URI
  2. http://fonts.googleapis.com/css?family=Indie+Flower替换为具有步骤1中的数据URI的版本
  3. 将步骤2中的文件转换为数据URI
  4. @import来自第3步的数据URI

网上有很多网站会创建数据URI.