代码之家  ›  专栏  ›  技术社区  ›  Escher

嵌入式svg未正确缩放

  •  0
  • Escher  · 技术社区  · 9 年前

    我试图在svg中嵌入svg(真正的应用程序是能够在d3图表中嵌入图像)。下面是一个简化版本:

    <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缩放到指定值 width 和 height ?

    编辑-使用Chrome而不是Firefox?!你知道为什么吗?

    2 回复  |  直到 9 年前
        1
  •  1
  •   Paul LeBeau    9 年前

    行为 <image> 在SVG 1.1和即将推出的SVG 2之间进行了一些更改。

    看起来Chrome正在遵循SVG 2的行为。Chrome在实现SVG 2方面似乎比其他浏览器走得更远。如果它仍然只支持SVG 1.1标准,则显示嵌入图像的方式将是错误的。

    Firefox(和IE,其行为相同)对于SVG 1.1都是不正确的 和 SVG 2.SVG 1.1标准规定,当 <图像> 没有 viewBox ,它应该只显示在 x 和 y 属性,以及 width 和 height 的 <图像> 元素被忽略。换句话说:

    <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>

    视窗 circle.svg 无论是否支持SVG 2,它都将在所有浏览器中呈现相同的结果。

    <svg xmlns="http://www.w3.org/2000/svg" width="335" height="296" viewBox="0 0 335 296">
    
        2
  •  0
  •   Fabio    9 年前

    我遇到了一个类似的问题,我们最终使用了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