图像元素不占用SVG中的完整矩形 - jquery

时间:2013-03-07 09:01:02

标签: jquery svg jquery-svg

请参阅以下SVG。

<svg width="5cm" height="4cm" version="1.1"
     xmlns="http://www.w3.org/2000/svg" xmlns:xlink= "http://www.w3.org/1999/xlink">

<rect x="0" y="0" width="150px" height="150px"/>

    <image xlink:href="firefox.jpg" x="0" y="0" height="150px" width="150px"/>
</svg>

输出如下所示。

enter image description here

如何让图片占据整个矩形?

谢谢,

希瓦

2 个答案:

答案 0 :(得分:1)

适用于与矩形具有相同宽高比的图像:http://jsfiddle.net/M24gX/

<svg width="8cm" height="8cm" version="1.1">
    <rect x="0" y="0" width="150px" height="150px" fill="red"/>
    <image xlink:href="http://lorempixel.com/150/150/sports/"
        x="0" y="0" height="150px" width="150px"/>
</svg>

对于具有与矩形不同的宽高比的图像不起作用:http://jsfiddle.net/5v9bd/

<svg width="8cm" height="8cm" version="1.1">
    <rect x="0" y="0" width="150px" height="150px" fill="red"/>
    <image xlink:href="http://lorempixel.com/300/150/sports/"
        x="0" y="0" height="150px" width="150px"/>
</svg>

如果您希望图像填充矩形的完整150x150px,无论其纵横比如何,您:

  • assign height =“150px”and width =“150px”(就像你已经做过的那样)
  • 指定preserveAspectRatio =“none”以允许图片具有非均匀缩放

示例:http://jsfiddle.net/Fq96J/

<svg width="8cm" height="8cm" version="1.1">
    <rect x="0" y="0" width="150px" height="150px" fill="red"/>
    <image xlink:href="http://lorempixel.com/300/150/sports/"
        x="0" y="0" height="150px" width="150px" preserveAspectRatio="none"/>
</svg>

preserveAspectRatio是一个你在使用SVG时应该清楚知道的属性,所以我建议阅读一些文档并稍微玩一下。

可以找到很好的解释

答案 1 :(得分:0)

它在my JSFiddle上运行正常。你能在JSFiddle上重现它吗?

<svg width="8cm" height="8cm" version="1.1"
     xmlns="http://www.w3.org/2000/svg" xmlns:xlink= "http://www.w3.org/1999/xlink">

<rect x="0" y="0" width="150px" height="150px" stroke="red" stroke-width="3"/>

    <image xlink:href="firefox.jpg" x="0" y="0" height="150px" width="150px"/>
</svg>