I would like to have an svg downloaded from my site as a png. Searching I found this code and I must say that everything works. The site is a project that will only be viewed from mobile https://7c81b.wineqrcode.com/ and I would like you to change the size of the downloaded image. Currently the photo is generated based on the size of the svg. Is there any way to get around this? Thanks
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);}