Fill an SVG path element with a background image without tiling or scaling

I would like to do something very similar to Fill an SVG path element with a background image , except that the solution proposed there will display an image to fill an entire area of ​​the background. I do not want it. If the image fills neither the entire height nor the entire width, I would just like it to rest within the shape of the path, and let it be. If I try to limit the behavior by changing the height / width attributes, the rendering simply scales the image until it fills at least one of the dimensions.

I assume this behavior makes sense as it uses patterns. I see that what I want is not really a "model". I just want to tickle the image in the middle of my form just as it is, and not make a template out of it. However, I want the shape boundaries defined by my SVG outline to crop the image rendering when the image size goes past those borders. I do not know yet to get this behavior, except for using the template for the fill attribute, as it was done in the answer to this question.

In a similar question: To add a background image (.png) to the SVG circle shape , the user at the very bottom seems to indicate that he used a filter and not a pattern to achieve what I want to achieve. However, when I try to do this, the actual form is not taken into account during rendering. The image is rendered without any relation to the boundaries of the form, which seems almost useless.

Is there any way in SVG to get this background image similar to a picture, but without actually splitting the image into a template?

+8
html image svg background-image
source share
1 answer

Just make the x , y , width and height template match the bounding box of your path. You can simply use "0", "0", "1" and "1" respectively, because patternUnits defaults to objectBoundingBox , so units are expressed relative to the bounding box. Then make the image in your template also width and height in the path limit field. This time you will need to use the "real" sizes.

The image will be centered automatically in the template, because the default preserveAspectRatio for <image> does exactly what you want.

 <svg width="600" height="600"> <defs> <pattern id="imgpattern" x="0" y="0" width="1" height="1"> <image width="120" height="250" xlink:href="http://lorempixel.com/animals/120/250/"/> </pattern> </defs> <path fill="url(#imgpattern)" stroke="black" stroke-width="4" d="M 100,50 L 120,110 150,90 170,220 70,300 50,250 50,200 70,100 50,70 Z" /> </svg> 
+14
source share

All Articles