Crop to fit an svg pattern

14,098

To get this to work, you need to understand how objectBoundingBox units work in SVG, and also how preserveAspectRatio works.

Object Bounding Box Units

The size and content of gradients, patterns and a number of other SVG features can be specified in terms of the size of the object (path, rect, circle) which is being painted by specifying objectBoundingBox as the unit. The opposite is always userSpaceOnUse, which uses the coordinate system that the shape is drawn in.

Object bounding box units are usually the default for declaring the size and position of the graphical fill element; you change this by setting the patternUnits property on the <pattern> element. However, user space units are usually the default for any units used in the content graphics; to change this you set the patternContentUnits property.

So first step: To create a pattern that completely fills the shape, you need to:

  • Declare the height and width of the pattern as 100% (or 1); these will by default be interpreted relative to the bounding box).
  • Declare patternContentUnits="objectBoundingBox".
  • Size the content (your image) so that it has a height and width of 1.

You cannot use 100% as a synonym for 1 object bounding box unit within the pattern content itself (i.e., the image dimensions); percentages are interpreted relative to the SVG size, not the objectBoundingBox.*

I should mention, since you say that your shapes are <path> elements, that the object bounding box is the smallest rectangle that is perpendicular to the coordinate system in which the path is drawn and contains all the path's points. It doesn't include stroke. For example a straight horizontal line has a zero-height bounding box; an angled line has a bounding box rectangle such that the line is the diagonal of the box. If your paths are awkwardly shaped and/or not very well aligned with the coordinate system, the bounding box can be much larger than the path.

Preserving Aspect Ratio

The preserveAspectRatio property applies to images and to any element that can have a viewBox property: the parent <svg>, nested <svg>, <symbol>, <marker> and <pattern>. For images, the aspect ratio is calculated from the image's inherent width:height ratio, for all the others it is calculated from the width:height numbers in the viewBox attribute.

For either type of element, if you declare a height or width for the element that doesn't match the aspect ratio, the preserveAspectRatio property determines whether the content will be stretched to fit (none), sized to fit one dimension and cropped in the other (slice) or shrunk to fit both dimensions with extra space (meet); for meet and slice options you also specify how to align the content in the space.

However, it is important to note that the aspect ratio of the space available is calculated in the current coordinate system, not in screen pixels. So if a higher-level viewBox or transformation has altered the aspect ratio, things can still be distorted even with a preserveAspectRatio property set on the current element.

The other thing to know is that the default value is usually not none. For both <image> and <pattern> elements, the default is xMidYMid meet -- i.e., shrink to fit and center. Of course, this default only has an impact on pattern elements if the pattern element has a viewBox property (otherwise, it's assumed to have no aspect ratio to preserve).

What value you want to use for preserveAspectRatio will depend on the image and design:

  • Should the image be stretched to fit the shape preserveAspectRatio="none"?
  • Should the image aspect ratio be maintained, but sized to completely fit in or cover the shape?

In the first case (stretch), you don't need to do anything to the <pattern> element (no viewBox means no aspect ratio control), but you do need to specifically turn off aspect ratio control on the image.

In contrast, if you want to avoid distortion of the image you will need to:

  • Set viewBox and preserveAspectRatio properties on the <pattern> element;
  • Set the preserveAspectRatio property on the <image> if you want something different than the default.

Working Example

This fiddle shows three ways of getting a pattern image to fill a shape.

  • The top row has aspect control turned off.

    <!-- pattern1 - no aspect ratio control -->
    <pattern id="pattern1" height="100%" width="100%"
             patternContentUnits="objectBoundingBox">
        <image height="1" width="1" preserveAspectRatio="none" 
               xlink:href="/*url*/" />
    </pattern>
    
  • The middle row has aspect ratio control on the <image> element so the picture is cropped to fit the pattern, but the picture is still distorted when the pattern is drawn in the rectangle because the objectBoundingBox units that define the coordinate system are different for height versus width. (The image in the circle isn't distorted because the circle's bounding box is a square.)

    <!-- pattern2 - aspect ratio control on the image only -->
    <pattern id="pattern2" height="100%" width="100%"
             patternContentUnits="objectBoundingBox">
        <image height="1" width="1" preserveAspectRatio="xMidYMid slice" 
               xlink:href="/*url*/" />
    </pattern>
    
  • The bottom row has preserveAspectRatio set on both the image and the pattern (and also a viewBox set on the pattern). The image gets cropped but not stretched.

    <!-- pattern3 - aspect ratio control on both image and pattern -->
    <pattern id="pattern3" height="100%" width="100%"
             patternContentUnits="objectBoundingBox" 
             viewBox="0 0 1 1" preserveAspectRatio="xMidYMid slice">
        <image height="1" width="1"  preserveAspectRatio="xMidYMid slice" 
               xlink:href="/*url*/" />
    </pattern>
    

Output from the JS fiddle example, showing the images described

Source image by Stefan Krause, from Wikimedia Commons. The original aspect ratio is 4:6 portrait mode.

* Correction on 2015-04-03

Share:
14,098

Related videos on Youtube

raphaeltm
Author by

raphaeltm

Co-founder of Éphémère Creative. Designer, developer, creator of digital experiences. Artist at heart.

Updated on June 04, 2022

Comments

  • raphaeltm
    raphaeltm almost 2 years

    I have patterns that each have a single image in them. I need the images to scale to the full width or height of their containers, which are paths, while retaining their proportions. Essentially, they need to behave like an html image might if you set min-width:100%; min-height:100%;

    I have not used svgs much before and do not know which attributes to change to get this type of behaviour. I've been trying all sorts of combinations of viewBox, preserveAspectRatio, patternUnits and more, but I cannot seem to get what I want.

  • raphaeltm
    raphaeltm almost 10 years
    Thanks for the wonderfully detailed response! I think the main thing I was missing was how to use preserveAspectRatio, but I learned a lot from this.
  • AmeliaBR
    AmeliaBR almost 10 years
    Glad you got it figured out. I decided that it was a intricate enough topic that it warranted a head-to-toe discussion that could help others in the future, instead of spending a dozen back-and-forth comments trying to figure out which piece of the puzzle was tripping you up.
  • Michael Mullany
    Michael Mullany almost 10 years
    Amelia, this is a fantastic explanation. You should consider contributing some version of this to the pattern element doc on webplatform.org - which needs content pretty badly
  • AmeliaBR
    AmeliaBR almost 10 years
    Thanks @MichaelMullany. Yes, I should take another look at webplatform.org and see if there's anything I can help. I like the idea of the project, but I know when I need to look something up myself I still tend to go back to MDN because it's more likely to have content.
  • AmeliaBR
    AmeliaBR almost 9 years
    @RobertLongson Happy to see that edit! Thanks for making that fix happen. I've got a similar correction to make in my book: I love turning "This doesn't work" warnings into "If this doesn't work, your user hasn't updated their browser lately".
  • Alexandr_TT
    Alexandr_TT almost 5 years
    @AmeliaBR Link fiddle not working Please correct if possible
  • AmeliaBR
    AmeliaBR almost 5 years
    @Alexandr_TT Link fixed. If you come across any others in the future, you need to replace http://fiddle.jshell.net with https://jsfiddle.net/.
  • Alexandr_TT
    Alexandr_TT almost 5 years
    @ AmeliaBR Thanks for the answer. And thanks for the great article that helped me figure out some of the nuances svg
  • Native Coder
    Native Coder almost 4 years
    I sincerely wish I could donate some of my rep to this answer. Thank you so much. I never even knew "Defs" was a thing, and probably never would have if not for this answer. D3 just got a hell of a lot easier.