代码直接附上
function svgToPng(svgStr, width, height, callback) {
// 创建Blob对象
var blob = new Blob([svgStr], { type: 'image/svg+xml' });
// 创建一个URL,指向Blob对象
var svgUrl = URL.createObjectURL(blob);
// 创建Image对象
var img = new Image();
img.crossOrigin = 'Anonymous'; // 处理跨域问题
img.onload = function() {
// 创建Canvas元素
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = width || img.width;
canvas.height = height || img.height;
// 将SVG图像绘制到Canvas上
ctx.drawImage(img, 0, 0, width || img.width, height || img.height);
// 导出Canvas为DataURL
var pngUrl = canvas.toDataURL('image/png');
// 创建一个<a>元素用于下载
var downloadLink = document.createElement('a');
downloadLink.href = pngUrl;
downloadLink.download = 'image.png';
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
// 释放URL对象
URL.revokeObjectURL(svgUrl);
// 回调函数
if (typeof callback === 'function') {
callback(pngUrl);
}
};
img.src = svgUrl;
}
svgString = '<svg width="100" height="100"><circle cx="50" cy="50" r="40" fill="blue"/></svg>'