在html中将svg标签转换为图片保存到本地
function exportSVGAsImage(svgElement, options = {}) {
const {
imageType = 'image/png',
width = svgElement.clientWidth,
height = svgElement.clientHeight,
fileName = 'exported-image',
color = getComputedStyle(svgElement.parentElement).color,
} = options;
// 克隆一份SVG,防止改动原始DOM
const clonedSVG = svgElement.cloneNode(true);
// 把 currentColor 全部替换成实际颜色
clonedSVG.querySelectorAll('*').forEach((node) => {
const fill = node.getAttribute('fill');
const stroke = node.getAttribute('stroke');
if (fill === 'currentColor') node.setAttribute('fill', color);
if (stroke === 'currentColor') node.setAttribute('stroke', color);
});
const serializer = new XMLSerializer();
let source = serializer.serializeToString(clonedSVG);
if (!source.match(/^<svg[^>]+xmlns="http:\/\/www.w3.org\/2000\/svg"/)) {
source = source.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"');
}
const svgBlob = new Blob([source], { type: 'image/svg+xml;charset=utf-8' });
const url = URL.createObjectURL(svgBlob);
const img = new Image();
img.onload = function () {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d');
context.drawImage(img, 0, 0, width, height);
URL.revokeObjectURL(url);
const imgURL = canvas.toDataURL(imageType);
const link = document.createElement('a');
link.href = imgURL;
link.download = `${fileName}.${imageType.split('/')[1]}`;
link.click();
};
img.crossOrigin = 'anonymous';
img.src = url;
}