1.遇到需要将svg下载的需求,网上找了一些代码,地址是这个https://github.com/exupero/saveSvgAsPng,但是不太好用,莫名的把网页所有的svg都下载了,于是在源码的基础上做了一些小的修改;代码如下所示
var doctype = '<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [<!ENTITY nbsp " ">]>'; function convertToPng(src, w, h) { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); canvas.width = w; canvas.height = h; context.drawImage(src, 0, 0); var png; try { png = canvas.toDataURL("image/png"); } catch (e) { if ((typeof SecurityError !== 'undefined' && e instanceof SecurityError) || e.name == "SecurityError") { console.error("Rendered SVG images cannot be downloaded in this browser."); return; } else { throw e; } } return png; } function isElement(obj) { return obj instanceof HTMLElement || obj instanceof SVGElement; } function reEncode(data) { data = encodeURIComponent(data); data = data.replace(/%([0-9A-F]{2})/g, function (match, p1) { var c = String.fromCharCode('0x' + p1); return c === '%' ? '%25' : c; }); return decodeURIComponent(data); } function uriToBlob(uri) { var byteString = window.atob(uri.split(',')[1]); var mimeString = uri.split(',')[0].split(':')[1].split(';')[0] var buffer = new ArrayBuffer(byteString.length); var intArray = new Uint8Array(buffer); for (var i = 0; i < byteString.length; i++) { intArray[i] = byteString.charCodeAt(i); } return new Blob([buffer], {type: mimeString}); } function downLoad(el, name) { if (!isElement(el)) { throw new Error('an HTMLElement or SVGElement is 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的选择器都可以;例如
<div id="svg-parent-div"><svg>...</svg></div>
一般通过获取svg的父元素来找到它,比如
var el = d3.select("#svg-parent-div").node().children[0]; download(el,"下载图片");
这样就可以了;
代码对于svg的没设置命名空间的情况做了处理,通过如下代码,如果svg 元素没有 设置命名空间,则添加;
el.setAttributeNS(xmlns, "xmlns", "http://www.w3.org/2000/svg"); el.setAttributeNS(xmlns, "xmlns:xlink", "http://www.w3.org/1999/xlink");
同时,添加的命名空间作用在clone的元素上,不会影响原来的svg元素;
总结
以上所述是小编给大家介绍的JavaScript 下载svg图片为png格式,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!
新闻热点
疑难解答