我想从我的网站下载一个svg作为png。搜索时我找到了这段代码,我必须说一切都正常。该网站是一个只能从手机查看的项目https://7c81b.wineqrcode.com/ 我希望您更改下载图像的大小。目前,照片是根据svg的大小生成的。有什么办法可以绕过这个问题吗?谢谢
function downloadSVGAsPNG(e){
const canvas = document.createElement("canvas");
const svg = document.querySelector(\'#Layer_1\');
const base64doc = btoa(unescape(encodeURIComponent(svg.outerHTML)));
const w = parseInt(svg.getAttribute(\'width\'));
const h = parseInt(svg.getAttribute(\'height\'));
const img_to_download = document.createElement(\'img\');
img_to_download.src = \'data:image/svg+xml;base64,\' + base64doc;
console.log(w, h);
img_to_download.onload = function () {
console.log(\'img loaded\');
canvas.setAttribute(\'width\', w);
canvas.setAttribute(\'height\', h);
const context = canvas.getContext("2d");
//context.clearRect(0, 0, w, h);
context.drawImage(img_to_download,0,0,w,h);
const dataURL = canvas.toDataURL(\'image/png\');
if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(canvas.msToBlob(), "download.png");
e.preventDefault();
} else {
const a = document.createElement(\'a\');
const my_evt = new MouseEvent(\'click\');
a.download = \'download.png\';
a.href = dataURL;
a.dispatchEvent(my_evt);
}
//canvas.parentNode.removeChild(canvas);
}
}
const downloadPNG = document.querySelector(\'#downloadPNG\');
if(downloadPNG) { downloadPNG.addEventListener(\'click\', downloadSVGAsPNG);}