download svg to png size image

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);}

Topic svg Wordpress javascript

Category Web


const w = parseInt(svg.getAttribute('width'));
const h = parseInt(svg.getAttribute('height'));

Change those 2 lines so that w and h have the desired values.

E.g.

const w = 101;

Will make the result 101 pixels wide


Prepare image in the backend. PHP has libraries for that. GD, or better yet, imagick if you have it installed / can install. So this is how it should work: Trigger image download in frontend (javascript). Start AJAX (fetch) call to backend. In the backend use PHP to convert and resize image. Return to javascript as a binary.

It is much more work, but it is much more solid solution. Other than that, you can look into javascript libraries for resizing images, but that would be slower and rely on client capabilities, which might not be sufficient.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.