javascript - 如何将带有剪切路径和蒙版的 SVG 放在图像 src 中?
问题描述
我已经尝试了很长一段时间,将动态生成的 SVG 放入图像“src”属性中,并且在简单的形状方面取得了成功,但是这个带有剪切路径和蒙版的形状不起作用。
我做错什么了吗。(尝试使用“use”和“defs”但没有运气)
任何帮助表示赞赏。例子:
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;
})();
如果您删除用于设置剪切路径和蒙版属性的部分,则它可以工作,但结果如您所料。这里生成或序列化错误的部分是什么?任何帮助表示赞赏。
解决方案
推荐阅读
- java - 这两种Java插入排序算法哪个更好?
- spring-boot - SpringBoot 执行器总是执行测试邮件
- javascript - JavaScript 自动提交表单
- algorithm - 在给定相同离散输入的情况下确定两个表面之间的误差?
- c++ - 如何隐藏 ShellExecuteEx 控制台窗口而不是应用程序窗口?
- sharepoint - Microsoft Graph API 不返回搜索结果
- c# - Parallel.For 循环退出太快
- facebook - react-native fbsdk 正在返回未定义的电子邮件
- freemarker - 包含空格的参数问题
- java - 从java中的XML中提取二进制数据