Convert 2 or more SVGs to PNG in JavaScript

102 Views Asked by At

I'm using the below code to convert 1 SVG to PNG. I convert the SVG to canvas to PNG.

getDownloadURL = async () => {
          // Logic to convert SVG to PNG

          const svg = document.querySelector('#widget svg'),
            canvas = new OffscreenCanvas(svg.clientWidth*3, svg.clientHeight*3),
            svgString = new XMLSerializer().serializeToString(svg),
            ctx = canvas.getContext('2d'),
            v = await Canvg.fromString(ctx, svgString, presets.offscreen());
          await v.render();
          const blob = await canvas.convertToBlob(),
            pngUrl = URL.createObjectURL(blob);

          return pngUrl;
}

download = filename => {
          const a = document.createElement('a');
          a.download = filename;
          getDownloadURL().then(url => {
            a.href = url;
            document.body.appendChild(a);
            a.click();
            a.remove();
          });
        };

If I try to convert more than 1 SVG by replacing const svg = document.querySelector('#widget svg') to const svg = document.querySelector('#widget') because #widget element has 2 SVGs, the resultant PNG has 2 SVGs overlapping each other.

How can I fix this overlapping issue? It would be great if I can render the content of element #widget as it is on PNG.

0

There are 0 best solutions below