Skip to content

Instantly share code, notes, and snippets.

@pudymody
Created April 27, 2023 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pudymody/c74c4f23de2a77bc3b849e1eb584aff9 to your computer and use it in GitHub Desktop.
Save pudymody/c74c4f23de2a77bc3b849e1eb584aff9 to your computer and use it in GitHub Desktop.
resvg-js blob demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta http-equiv="Cache-Control" content="no-cache">
<title>Resvg-js blob demo</title>
</head>
<body>
<input type="file" />
<svg viewBox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg"><image href="" height="1000" width="1000" /></svg>
<img src="" id="output" />
<script src="https://unpkg.com/@resvg/resvg-wasm"></script>
<script>
const $button = document.querySelector("input");
const $img = document.querySelector("image");
const $svg = document.querySelector("svg");
$button.addEventListener("change", function(e){
const url = window.URL.createObjectURL(e.target.files[0]);
$img.setAttribute("href", url);
});
async function save(){
// The Wasm must be initialized first
await resvg.initWasm(fetch('https://unpkg.com/@resvg/resvg-wasm/index_bg.wasm'))
const opts = {}
const resvgJS = new resvg.Resvg($svg.outerHTML, opts)
const resolved = await Promise.all(
resvgJS.imagesToResolve().map(async (url) => {
console.info('image url', url)
const img = await fetch(url)
const buffer = await img.arrayBuffer()
return {
url,
buffer: Buffer.from(buffer),
}
}),
)
if (resolved.length > 0) {
for (const result of resolved) {
const { url, buffer } = result
resvgJS.resolveImage(url, buffer)
}
}
const pngData = resvgJS.render()
const pngBuffer = pngData.asPng()
document.querySelector('#output').src = URL.createObjectURL(
new Blob([pngBuffer], { type: 'image/png' })
)
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment