Skip to content Skip to sidebar Skip to footer

How Does SVG Image Pattern Work With Preserving Aspect Ratio?

I have the following svg: It's not working as expected because it enlarge te face of the people on the image as follows: But it should look like this: Does having a triangular

Solution 1:

Well this is working as intended. You specify a pattern whose unit should fill the bounding box of the container, and then specify a 2:1 container - so it stretches the image. There are lots of permutations that preserve the aspect ratio of the image - it depends on exactly what behavior you want.

This is one version that preserves the aspect ratio of the SVG itself even when it's asked to fill a larger space.

<svg height="100%" width="100%" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice" style="display: block; position: absolute; top: 0;">
    <defs>
        <pattern id="img1" patternUnits="objectBoundingBox" width="100%" height="100%">
            <image xlink:href="https://media.npr.org/assets/img/2016/06/22/gettyimages-467390112_custom-e8fa0c9a7224b7172555577fde25a08949bde2d2-s900-c85.jpg" x="0" y="-20" width="100" height="100"/>
          </pattern>
    </defs>
        <polygon points="0 100, 50,50 100,100" id="abajo"  fill="url(#img1)" />
    </svg>

Or if you want to adjust the pattern itself, you can double the height of the pattern and offset it in Y to adjust for the 2:1 ratio of your container:

<svg height="100%" width="100%" viewBox="0 0 100 100"  style="display: block; position: absolute; top: 0;">
    <defs>
        <pattern id="img1" patternUnits="objectBoundingBox" y="-100%" width="100%" height="200%">
            <image xlink:href="https://media.npr.org/assets/img/2016/06/22/gettyimages-467390112_custom-e8fa0c9a7224b7172555577fde25a08949bde2d2-s900-c85.jpg" x="0" y="0" width="100" height="100" preserveAspectRatio="xMidYMax meet"/>
          </pattern>
    </defs>
        <polygon points="0 100, 50,50 100,100" id="abajo"  fill="url(#img1)" />
    </svg>

This is another version that uses a filter to fill in the image.

<svg height="100%" width="100%" viewBox="0 0 100 100" style="display: block; position: absolute; top: 0; background:grey">
    <defs>
        <filter id="img1" x="0%" y="0%" width="100%" height="100%" >
            <feImage xlink:href="https://media.npr.org/assets/img/2016/06/22/gettyimages-467390112_custom-e8fa0c9a7224b7172555577fde25a08949bde2d2-s900-c85.jpg" x="0" y="0" width="100" height="100" preserveAspectRatio="xMidYMax meet"/>
             <feComposite operator="in" in2="SourceGraphic"/>
          </filter>
    </defs>
        <polygon points="0 100, 50,50 100,100" id="abajo"  filter="url(#img1)" />
    </svg>

Post a Comment for "How Does SVG Image Pattern Work With Preserving Aspect Ratio?"