I have been trying for quite a while now to put dynamically generated SVG in an image "src" attribute and have been successful with the simple shapes but this one with clipping path and mask just doesn't work.
Did I do something wrong. (Tried with "use" and "defs" but no luck)
Any help is appreciated. Example:
function createSVG(){
const ns = 'http://www.w3.org/2000/svg';
const shapeSvg = document.createElementNS(ns, "svg");
shapeSvg.setAttribute('width', '50px');
shapeSvg.setAttribute('height', '50px');
shapeSvg.setAttribute("width", "50px");
shapeSvg.setAttribute("height", "50px");
// Make clipping path
const clipPath = document.createElementNS(ns, "clipPath");
clipPath.setAttributeNS(null, "id", "clipPath");
const cPath = document.createElementNS(ns, "path");
cPath.setAttributeNS(null, "d", "M 25 0 A 25 25, 0, 1, 1, 0 25 L 0 0 Z");
clipPath.appendChild(cPath);
shapeSvg.appendChild(clipPath);
// Make mask path
const mask = document.createElementNS(ns, "mask");
mask.setAttributeNS(null, "id", "circleMask");
const mRect = document.createElementNS(ns, "rect");
mRect.setAttributeNS(null, "x", 0);
mRect.setAttributeNS(null, "y", 0);
mRect.setAttributeNS(null, "width", "50px");
mRect.setAttributeNS(null, "height", "50px");
mRect.setAttributeNS(null, "fill", "white");
mask.appendChild(mRect);
const mCircle = document.createElementNS(ns, "circle");
mCircle.setAttributeNS(null, "cx", 25);
mCircle.setAttributeNS(null, "cy", 25);
mCircle.setAttributeNS(null, "r", 25);
mCircle.setAttributeNS(null, "fill", "black");
mask.appendChild(mCircle);
shapeSvg.appendChild(mask);
const tailPath = document.createElementNS(ns, "path");
tailPath.setAttributeNS(null, "d", "M 0 0 L 0 25 L 25 0 Z");
tailPath.setAttributeNS(null, "fill", "black");
tailPath.setAttributeNS(null, "mask", "url(#circleMask)");
shapeSvg.appendChild(tailPath);
const tearPath = document.createElementNS(ns, "path");
tearPath.setAttributeNS(null, "d", "M 25 0 A 25 25, 0, 1, 1, 0 25 L 0 0 Z");
tearPath.setAttributeNS(null, "stroke", "black");
tearPath.setAttributeNS(null, "stroke-width", "3");
tearPath.setAttributeNS(null, "fill", "none");
tearPath.setAttributeNS(null, "clip-path", "url(#clipPath)");
shapeSvg.appendChild(tearPath);
return shapeSvg;
}
(function createShape(){
const container = document.body;
const svg = createSVG();
document.body.prepend(svg);
var xml = (new XMLSerializer).serializeToString(svg);
var image = document.createElement('img');
image.src = `data:image/svg+xml,${xml}`;
image.style.cssText = `
width:50px;
height:50px;
`;
container.appendChild(image);
return container;
})();
If you remove the part for setting the attributes for clipping-path and mask it works but the result is as you can guess. What part is generated or serialized wrong here? Any help is appreciated.