IE可以在“img”元素中呈现SVG嵌入图像,但Chrome/Firefox不能。

3

我试图使用 "img" 标签引用 SVG 文件:

<img width="200" height="100"
     src="test.svg" 
     onerror="this.onerror = null; alert('error');"
     />

通常这个方法是有效的,但是如果“test.svg”中有一个嵌入的.jpg图像,则该图像无法呈现。这在Chrome和Firefox中都是正确的 - IE可以正确地呈现图像。奇怪的是,如果我直接在浏览器中加载“test.svg”,则每个浏览器上的嵌入式图像都会正确呈现。

以下是一个显示我的意思的“test.svg”示例:

<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     width="200" height="100">

    <!-- Text and shapes always render correctly -->
    <text x="20" y="20" font-size="20">some text</text>
    <ellipse ry="30" rx="30" 
             cy="50" cx="50" 
             stroke-width="5" stroke="#000000" 
             fill="#FF0000" 
             />

    <!-- Embedded images render in IE, but not in Chrome or Firefox -->
    <image xlink:href="test.jpg"
           width="100" height="100"
           x="100" />
</svg>

我找不到一个明确的答案。这是Webkit的一个bug吗?
2个回答

3
任何通过<img>标签嵌入的SVG图像必须是自包含的。 它所引用的任何外部资源,如图像、字体或CSS文件,都将不会被加载。
这样做的原因在此处解释:https://bugzilla.mozilla.org/show_bug.cgi?id=628747 FF和Webkit已经做了这个改变。 我想IE还没有。

啊,谢谢。你有相关参考资料吗?我查看了SVG规范,但没有找到相关内容。 - McGarnagle
1
如果需要的话,您可以将图像和其他资源嵌入为数据URL。 - Paul LeBeau
有趣的是,我在想,IE竟然是一个更好的浏览器,这真是个奇迹;但实际上,它只是另一个安全漏洞。 - McGarnagle

0
你可以使用一个带有可选回退的标签来更好地处理SVG。这里是你可以做的事情 -
<object width="200" height="100" data='test.svg' onerror="this.onerror = null; alert('error');">
    <!-- fallback -->
    <img width="200" height="100" src="test.svg" onerror="this.onerror = null; alert('error');" />
</object>

在这里,你的对象标签将被首先加载,如果由于某种原因失败,则会加载你的备用方案。在这种情况下,我已经将你原来的img作为备选方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接