I want to use clipPath
for an image I'm trying to display on my webpage, and I want to be able to use percentages instead of absolute points with polygon
. I've tried adding the viewBox
attribute to my svg element to do so (suggested here SVG polygon points with percentage units support), but when the image renders, it looks like absolute points are still being used. I have my html setup like this:
<img src="{% static 'myApp/images/random.png' %}">
<div id="svg-container" style="width:100%; height:100%;">
<svg width='100%' height='100%' viewBox="0 0 100 100">
<defs>
<clipPath id="myClip">
<polygon points="89,0 100,50 89,100 71,100 83,50 69,0"/>
<polygon points="53,0 75,50 59,100 48,100 64,50 41,0" />
</clipPath>
</defs>
</svg>
</div>
With the CSS being:
.clip-svg {
clip-path: url(#myClip);
}
Just using CSS clip-path (without svg) I had:
clip-path: polygon(89% 0, 100% 50%, 89% 100%, 71% 100%, 83% 50%, 69% 0);
clip-path: polygon(53% 0, 75% 50%, 59% 100%, 48% 100%, 64% 50%, 41% 0);
When I used to the CSS clip-path
style, the clips display correctly, I can just only display one at a time and I wanted both at once. All the other similar questions I've read just say to use the viewBox
attribute which I've done, so I can't figure out what's going wrong.
CodePudding user response:
You may try to use clipPathUnits="objectBoundingBox"
for the clipPath.
This indicates that all coordinates inside the
<clipPath>
element are relative to the bounding box of the element the clipping path is applied to. It means that the origin of the coordinate system is the top left corner of the object bounding box and the width and height of the object bounding box are considered to have a length of 1 unit value.
Plrase read about clipPathUnits
Please observe that the polygons have transform="scale(.01)"
i.e 1/100. Now the values are percentages.
.clip-svg {
clip-path: url(#myClip);
}
img{width:95vw;}
<img src="https://assets.codepen.io/222579/castell.jpg" />
<svg viewBox="0 0 100 100" width="0" height="0">
<clipPath id="myClip" clipPathUnits="objectBoundingBox">
<polygon transform="scale(.01)" points="89,0 100,50 89,100 71,100 83,50 69,0" />
<polygon transform="scale(.01)" points="53,0 75,50 59,100 48,100 64,50 41,0" />
</clipPath>
</svg>
Also: the svg element used for clipPath can have width="0" height="0"
so that it doesn't interfere with the layout.