Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stretch an image in a SVG shape to fill its bounds?

Tags:

html

css

svg

I have an SVG shape (a parallelogram) which is filled with an image. The demo can be seen here.

The SVG object is:

<svg style="overflow:visible; margin-left:111px; margin-top:22px; " height="86" width="281">
    <defs>
        <pattern id="blip1" patternUnits="userSpaceOnUse" width="279" height="83">
            <image xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://i.imgur.com/uTDpE6J.jpg" width="279" height="83"></image>
        </pattern>
    </defs>
    <polygon points="49,2 280,2 232,84 1,84" x="1" y="1" style="stroke-linejoin:round; fill:url(#blip1); stroke-width:2; stroke:hsl(212,45%,26%); "></polygon>
</svg>

But the image is not stretched to the bounds of the shape, instead it lies in the middle of the shape.

What I am trying to achieve is this:

Desired result

But what I am getting is this:

Actual result

Can anyone suggest me a solution that will apply to all shapes (i.e. pentagon, hexagon, star etc.)? BTW it already works fine with ellipses.

like image 799
Surender Thakran Avatar asked Dec 18 '13 13:12

Surender Thakran


1 Answers

Adding preserverAspectRatio=none to the image object and setting width/height to 100% seems to do what you want. Updated fiddle

<svg style="overflow:visible; margin-left:111px; margin-top:22px; " height="86" width="281">

    <defs>
        <pattern id="blip1" patternUnits="userSpaceOnUse" width="279" height="83">
             <image preserveAspectRatio="none" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://i.imgur.com/uTDpE6J.jpg" width="279" height="83"></image>
        </pattern>
    </defs>

    <polygon points="49,2 280,2 232,84 1,84" x="1" y="1" style="stroke-linejoin:round; fill:url(#blip1); stroke-width:2; stroke:hsl(212,45%,26%); ">
    </polygon>

</svg>
like image 177
olly_uk Avatar answered Nov 10 '22 06:11

olly_uk