[javascript] Convert SVG to image (JPEG, PNG, etc.) in the browser

The solution to convert SVG to blob URL and blob URL to png image

_x000D_
_x000D_
const svg=`<svg version="1.1" baseProfile="full" width="300" height="200"_x000D_
xmlns="http://www.w3.org/2000/svg">_x000D_
   <rect width="100%" height="100%" fill="red" />_x000D_
   <circle cx="150" cy="100" r="80" fill="green" />_x000D_
   <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">SVG</text></svg>`_x000D_
svgToPng(svg,(imgData)=>{_x000D_
    const pngImage = document.createElement('img');_x000D_
    document.body.appendChild(pngImage);_x000D_
    pngImage.src=imgData;_x000D_
});_x000D_
 function svgToPng(svg, callback) {_x000D_
    const url = getSvgUrl(svg);_x000D_
    svgUrlToPng(url, (imgData) => {_x000D_
        callback(imgData);_x000D_
        URL.revokeObjectURL(url);_x000D_
    });_x000D_
}_x000D_
function getSvgUrl(svg) {_x000D_
    return  URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }));_x000D_
}_x000D_
function svgUrlToPng(svgUrl, callback) {_x000D_
    const svgImage = document.createElement('img');_x000D_
    // imgPreview.style.position = 'absolute';_x000D_
    // imgPreview.style.top = '-9999px';_x000D_
    document.body.appendChild(svgImage);_x000D_
    svgImage.onload = function () {_x000D_
        const canvas = document.createElement('canvas');_x000D_
        canvas.width = svgImage.clientWidth;_x000D_
        canvas.height = svgImage.clientHeight;_x000D_
        const canvasCtx = canvas.getContext('2d');_x000D_
        canvasCtx.drawImage(svgImage, 0, 0);_x000D_
        const imgData = canvas.toDataURL('image/png');_x000D_
        callback(imgData);_x000D_
        // document.body.removeChild(imgPreview);_x000D_
    };_x000D_
    svgImage.src = svgUrl;_x000D_
 }
_x000D_
_x000D_
_x000D_