To convert SVG into PNG in the browser, you can use the Resvg-js wasm module.
Setting up the project
- Create an
index.htmlfile and fetchresvg-wasmmodule.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <img id="output"> <script src="https://unpkg.com/@resvg/resvg-wasm"></script> </body> </html> - Create an
index.jsfile and link it to theindex.htmlfile.
<script type="module" src="./index.js"></script> Working with Resvg-wasm
Inside the index.js file, I am using an IFEE function expression. You can also add some event handlers to invoke javascript functions. But for simplicity, the code inside index.js will run immediately when the page loads.
- First, initialize the
resvg-wasmmodule using theinitWasmmethod.
await resvg.initWasm( fetch("https://unpkg.com/@resvg/resvg-wasm/index_bg.wasm") ); - Now defining some options. You can check out for more options in the documentation.
const opts = { fitTo: { mode: "width", // If you need to change the size value: 800, }, }; - This is the final part. Convert an SVG image into a PNG image using
resvg-wasm
const svg ='<svg>...</svg>'; // Input SVG, String or Uint8Array const resvgJS = new resvg.Resvg(svg, opts); const pngData = resvgJS.render(svg, opts); // Output PNG data, Uint8Array const pngBuffer = pngData.asPng(); const pngURL = URL.createObjectURL( new Blob([pngBuffer], { type: "image/png" }) ); document.getElementById("output").src = pngURL; - Wrap the code inside an IFEE to invoke immediately on page load.
(async function () { await resvg.initWasm( fetch("https://unpkg.com/@resvg/resvg-wasm/index_bg.wasm") ); const opts = { fitTo: { mode: "width", // If you need to change the size value: 800, }, }; const svg ='<svg>...</svg>'; // Input SVG, String or Uint8Array const resvgJS = new resvg.Resvg(svg, opts); const pngData = resvgJS.render(svg, opts); // Output PNG data, Uint8Array const pngBuffer = pngData.asPng(); const pngURL = URL.createObjectURL( new Blob([pngBuffer], { type: "image/png" }) ); document.getElementById("output").src = pngURL; })(); Further read:
Top comments (1)
yo thank you so much for writing this. I spent the whole day first figuring out how to create dynamic image and then found out I needed png or jpg and cloudflare doesn't support nodejs based packages.
Again thanks. keep writing.