Search code examples
jquerysvgjquery-svg

Image element not occupying the full rectangle in SVG - jquery


Please refer the below 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>

The output looks like below.

enter image description here

How can i make the image to occupy the full rectangle ?

Thanks,

Siva


Solution

  • Works for images having the same aspect ratio as your rect: 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>
    

    Doesn't work for images having a different aspect ratio as your rect: 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>
    

    If you want the image to fill the full 150x150px of the rectangle regardless of its aspect ratio, you:

    • assign height="150px" and width="150px" (like you already did)
    • assign preserveAspectRatio="none" to allow the image to have a non-uniform scaling

    Example: 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 is an attribute you should definitely know inside out when working with SVG so i recommend to read some docs and play around with it a bit. Good explanation can be found at