Aleksandar
Aleksandar

Reputation: 3661

SVG: stretching an image

I'm playing around with the SVG tutorial and I simply loaded an image like this:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg style="stroke-linejoin:round; stroke:black; stroke-width:0.5pt; text-anchor:middle; fill:none" xmlns="http://www.w3.org/2000/svg" font-family="Helvetica, Arial, FreeSans, Sans, sans, sans-serif" height="400px" width="400px" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 250 250">
    <rect y="0" x="0" height="250" width="250" stroke="black"  stroke-width="1" fill="blue" />
    <image y="0" x="0" height="250" width="250" xlink:href="http://www.blueprintmodel.co.uk/images/DSCF1438.jpg" />
</svg>

I get image in the center of viewBox, over "rect", even if height and width are same. My questions are:

Upvotes: 57

Views: 40596

Answers (4)

Michael Klishevich
Michael Klishevich

Reputation: 1864

I did this to stretch an image to fill the parent SVG, which has worked nicely.

<svg xmlns="http://www.w3.org/2000/svg" width="300px" height="200px" x="100" y="100" style="visibility: visible; opacity: 1;">
  <image href="my_image" preserveAspectRatio="none" width="100%" height="100%"></image>
</svg>

Upvotes: 0

peterhil
peterhil

Reputation: 1576

When working with SVG images, please learn about how preserveAspectRatio works — with it, you can make the SVG images responsive in any way you like!

https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/preserveAspectRatio

To answer your questions:

  • How do I stretch an image to be size of rect?

    <image viewBox="0 0 250 250" preserveAspectRatio="none" … />

  • Why "height" in "image" tag doesn't do the job?

    I don’t know what the problem with the image was because the original image is gone. Anyway, with SVG you should concentrate on using viewBox instead of width and height. You know, the name contains the word ‘scalable’, and using width and height prevents that…

  • Is there transformation like "stretch" or "resize" that I can use?

    Centered and contained:
    <image viewBox="0 0 250 250" preserveAspectRatio="xMidYMid meet" …

    Centered and covered:
    <image viewBox="0 0 250 250" preserveAspectRatio="xMidYMid slice" …

PS. Everything you need ever wanted to know about gotchas in scaling SVG images (but please forget about IE already, and do not use the padding-bottom hacks): https://css-tricks.com/scale-svg/

Upvotes: 5

Robert Longson
Robert Longson

Reputation: 124299

Set preserveAspectRatio="none" on the SVG element:

<svg viewBox="0 0 500 500" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg" >

Upvotes: 123

miir
miir

Reputation: 1936

It is also possible scale and change the aspect ratio of an SVG by using pure CSS:

transform: scale(x, y);

Upvotes: 8

Related Questions