1.遇到需要将svg下载的需求,网上找了一些代码,地址是这个nofollow" href="https://github.com/exupero/saveSvgAsPng">https://github.com/exupero/saveSvgAsPng,但是不太好用,莫名的把网页所有的svg都下载了,于是在源码的基础上做了一些小的修改;代码如下所示
required; got ' + el);
}
if (!name) {
console.error("文件名为空!");
return;
}
var xmlns = "http://www.w3.org/2000/xmlns/";
var clone = el.cloneNode(true);
clone.setAttribute("version","1.1");
if (!clone.getAttribute('xmlns')) {
clone.setAttributeNS(xmlns,"xmlns","http://www.w3.org/2000/svg");
}
if (!clone.getAttribute('xmlns:xlink')) {
clone.setAttributeNS(xmlns,"xmlns:xlink","http://www.w3.org/1999/xlink");
}
var svg = clone.outerHTML;
var uri = 'data:image/svg+xml;base64,' + window.btoa(reEncode(doctype + svg));
var image = new Image();
image.onload = function () {
var png = convertToPng(image,image.width,image.height);
var saveLink = document.createElement('a');
var downloadSupported = 'download' in saveLink;
if (downloadSupported) {
saveLink.download = name + ".png";
saveLink.style.display = 'none';
document.body.appendChild(saveLink);
try {
var blob = uriToBlob(png);
var url = URL.createObjectURL(blob);
saveLink.href = url;
saveLink.onclick = function () {
requestAnimationFrame(function () {
URL.revokeObjectURL(url);
})
};
} catch (e) {
saveLink.href = uri;
}
saveLink.click();
document.body.removeChild(saveLink);
}
};
image.src = uri;
}
这里使用的时候只需要调用download方法就可以了,建议封装成一个单独的下载服务;download方法的第一个参数el指的是dom元素,就是svg元素,具体的获取方法通过js或者d3的选择器都可以;例如
...