我已经尝试了很长时间,将动态生成的SVG放在图像“ src”属性中,并且已经成功使用简单的形状,但是这种带有剪切路径和蒙版的形状却不起作用。
我做错了什么。 (尝试过“使用”和“定义”,但没有运气)
感谢您的帮助。示例:
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;
})();
如果删除用于设置剪切路径和蒙版属性的零件,则它可以工作,但结果是您可以猜测的。哪一部分生成或序列化错误?任何帮助表示赞赏。