通过 canvas 将 svg 元素生成图片的形式,其中图片的大小取决于 svg 元素的复杂度。
const svgString = new XMLSerializer().serializeToString(document.querySelector('svg'));
const canvas = document.createElement('canvas');
const ctx = canvas.getContext("2d");
const svgElement = document.querySelector('.svgElement');
canvas.width = svgElement.clientWidth;
canvas.height = svgElement.clientHeight;
const DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([svgString], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
const png = canvas.toDataURL("image/png");
console.log(png) // base64 的 url
// document.querySelector('#png-container').innerHTML = '<img src="'+png+'"/>';
DOMURL.revokeObjectURL(png);
};
img.src = url;