2016-11-22 62 views
0

我试图在svg中嵌入svg(真正的应用是能够在d3图表中嵌入图像)。下面是一个简化版本:嵌入式svg没有正确缩放

<svg viewBox="0 0 200 200" version="1.1" 
    xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink"> 
    <circle cx="0" cy="0" r="80" style="fill:blue" /> 
    <image x="10" y="20" width="120" height="150" xlink:href="https://webkit.org/blog-files/circle.svg" /> 
</svg> 

嵌入式图像缩放正确的,如果它是一个光栅图像(PNG/JPG),但不包括SVG。这是一个小提琴不起作用 - 大红色矩形实际上应该是this circle

https://jsfiddle.net/rg4kyuc7/1/

如何获得SVG缩放到指定widthheight

编辑 - 使用Chrome而不使用Firefox?任何想法为什么?

回答

1

的MDN文档<image>行为改变SVG 1.1和即将到来的SVG 2.

它看起来像铬之间的小遵循SVG 2的行为。 Chrome似乎在实现SVG 2方面比其他浏览器更进一步。如果它仍然只支持SVG 1.1标准,它显示嵌入式图像的方式将会是错误的。

火狐(和IE,其表现是相同的)都相对于两个不正确的SVG 1.1 SVG 2. SVG 1.1标准说,当通过<image>引用的SVG文件没有viewBox,它应该只是被显示在由xy属性定义的位置处,并且<image>元件的widthheight被忽略。换句话说这样的:

<svg viewBox="0 0 200 200" version="1.1" 
 
    xmlns="http://www.w3.org/2000/svg" 
 
    xmlns:xlink="http://www.w3.org/1999/xlink"> 
 
    <circle cx="0" cy="0" r="80" style="fill:blue" /> 
 
    <image x="10" y="20" width="335" height="296" xlink:href="https://webkit.org/blog-files/circle.svg" /> 
 
</svg>

在任何情况下,有一个简单的解决。添加适当的viewBoxcircle.svg,它将在所有浏览器中呈现相同的效果,无论它们是否支持SVG 2。

<svg xmlns="http://www.w3.org/2000/svg" width="335" height="296" viewBox="0 0 335 296"> 
0

我遇到过类似的问题,我们最终使用了SVG的标签。

这样你就可以在其中嵌入一个html img标签,并将其样式化。事情是这样的:

<svg viewBox="0 0 200 200" version="1.1" 
    xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink"> 
    <circle cx="0" cy="0" r="80" style="fill:blue" /> 
    <foreignObject x="10" y="20" width="120" height="150" 
        requiredExtensions="http://www.w3.org/1999/xhtml"> 
     <body xmlns="http://www.w3.org/1999/xhtml"> 
     <img src="https://webkit.org/blog-files/circle.svg" alt="Smiley face" height="150" width="120"> 
     </body> 
    </foreignObject> 
</svg> 

这里是

https://developer.mozilla.org/en/docs/Web/SVG/Element/foreignObject