0

I have an SVG document with an emebedded image element like so:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" viewBox="0 0 200 200">
  <image xlink:href="hannibal.jpg" x="0" y="0" width="200" height='200' />
</svg>

I can't know ahead of time the width and height of the linked image.

How can I set the width of the image to be the same as the viewBox, and allow the height to autoscale?

Failing this, can I align the image content to the top of the image element?

superluminary
  • 47,086
  • 25
  • 151
  • 148
  • Have you tried setting width/height/both to 100% or just removing them? – haldagan May 08 '15 at 16:45
  • If you remove them the image is not displayed. Set them to 100% and they gain the width and height of the viewbox with the image content centered inside. – superluminary May 08 '15 at 16:52
  • Well, there is kinda similar question: http://stackoverflow.com/questions/6884513/how-to-get-the-real-unscaled-size-of-an-embedded-image-in-the-svg-document Is the first answer any help to you? – haldagan May 08 '15 at 17:01
  • Perhaps JavaScript is the solution. It just seems like there ought to be an SVG solution to embedding an image with the correct width and height. – superluminary May 08 '15 at 17:39
  • By autoscale do you mean that it must cover the svg doc? – Kaiido May 09 '15 at 11:13
  • Ideally I would like the SVG doc to be the same size as the image. The reason is that I want to be able to mask the image with a complex SVG shape. I would settle for simply ensuring the image sat correctly at the top of the svg. I suspect the solution is JavaScript. – superluminary May 09 '15 at 12:45

1 Answers1

0

If you want the image to be at the top of the viewBox, rather than the centre, you just have to set preserveAspectRatio="xMidYMin".

<svg version="1.1" xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" viewBox="0 0 200 200">
  <image xlink:href="hannibal.jpg" x="0" y="0" width="200" height="200"
         preserveAspectRatio="xMidYMin"/>
</svg>

This should work as long as the height is never greater than the width.

Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181