SVG is a fantastic technology that is becoming increasingly popular as our web browsers get increasingly more powerful. I actually think that SVG offers many advantages over Canvas.
SVG is a vector graphics format, but it also allows raster images to be used. Naturally, when zooming in, your raster images will lose quality as they have a ‘digital zoom’ applied. It is also possible to draw the image at a different size as the source file, for example you could use a 1×1 image and draw it at 100×100. If you want to see what that looks like, I’ve made you a demo.
But what happens if your source image is 100×100, and you draw it with a height of 100 and a width of 75? (Write down your answer if you have some paper!)
If you answered that the image would get scaled to fill the 75×100 hole, congratulations! You’re wrong. That was my assumption, too. The reason is likely because we have been conditioned to think this way with other web technologies – after all, it’s what happens when you draw an image with HTML, CSS, and even on Canvas.
What actually happens is that the image will only occupy 75×75 – it maintains its aspect ratio. I have made a demo to demonstrate this. (Remember to view source to see what’s going on).
If you’re using Inkscape, you may be confused by this (I sure was!), as their implementation will scale to fill the hole…
Unfortunately, it’s a bug.
There’s actually an attribute for the image tag in SVG that controls this behavior – the preserveAspectRatio attribute. This will need to be set to “none” in order to make the image scale to fill the hole.
So if you’re ever drawing images in SVG, be careful, and if you need to alter the aspect ratio from the original, make sure you are using preserveAspectRatio=”none”.
Did you guess correctly, and what are your thoughts on this? Personally, I find the value =”none” a little strange – I would have expected a true or false value. They’ve actually made it a little more powerful than this to give you more control over the behavior when the image is preserving aspect ratio.
This post is part of our “SVG Article Index” in these articles, we aim to help you build knowledge and understand SVG.
Latest posts by Leon Atherton (see all)
- Do you still need IE8 support in JPDF2HTML5? - February 8, 2017
- JPDF2HTML5 2016 Roundup and looking ahead to 2017 - December 20, 2016
- What Chrome 45 dropping NPAPI Plug-in support means - September 10, 2015
- The New JPDF2HTML5 API - May 26, 2015
- Upcoming JPDF2HTML5 Changes – Request for Feedback - April 14, 2015