I am trying to create an image with an SVG mask layer over it. I have 3 different svg paths being stored in a js array and based on which one the user pics (using a select box) a different mask should appear over the image. The problem is that the clip-paths are not all the same size.
How can I scale them so that whichever mask/clip-path the user selects will scale to fit properly over the entire image? I want to do this programmatically as eventually these paths will be user generated so I won't know what size they will be.
The image will always be the same size 400px X 400px and I'd like the scaled svg path mask to be centered in that frame if the scaled image doesn't take up the entire height or width.
Any help would be greatly appreciated.
var nomask = "M0 0 L400 0 L400 400 L0 400 L0 0 z";
var heart = "M 321.4214 178.5786 l -141.4214 141.4214 l -141.4214 -141.4214 a 100 100 315 0 1 141.4214 -141.4214 a 100 100 315 0 1 141.4214 141.4214 z";
var star = "M 22.928 118.8 l 35.12 -18.048 l 35.112 18.048 l -7.856 -46.032 l 23.328 -34.752 l -34.488 3.28 L 60.304 7.376 L 42.832 40.96 l -39.184 5.568 l 28.184 26.848 l -6.64 37.84 z";
var blob = "M215,100.3c97.8-32.6,90.5-71.9,336-77.6\
c92.4-2.1,98.1,81.6,121.8,116.4c101.7,149.9,53.5,155.9,14.7,178c-96.4,54.9,5.4,269-257,115.1c-57-33.5-203,46.3-263.7,20.1\
c-33.5-14.5-132.5-45.5-95-111.1C125.9,246.6,98.6,139.1,215,100.3z";
var masks = [nomask, star, blob, heart];
function changeMask(mask) {
document.getElementById("svgPath").children[0].setAttribute('d', masks[mask]);
}
body {
margin: 10px;
}
.imageContainer {
margin: 5px 0;
border: 1px solid black;
padding: 5px;
width: fit-content;
}
.clippingMask {
-webkit-clip-path: url(#svgPath);
clip-path: url(#svgPath);
}
<select id="maskSelect" onchange="changeMask(this.value);">
<option value="1">star</option>
<option value="2">blob</option>
<option value="3">heart</option>
<option value="0" selected>- no mask -</option>
</select>
<div class="imageContainer">
<img class="clippingMask" src="https://picsum.photos/400">
</div>
<svg height="0" width="0">
<defs>
<clipPath id="svgPath">
<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10"
d="M0 0 L400 0 L400 400 L0 400 L0 0 z" />
</clipPath>
</defs>
</svg>
Note that in my example to star is much to small and the blob is too big.
Thanks!