-
-
Save pudymody/c74c4f23de2a77bc3b849e1eb584aff9 to your computer and use it in GitHub Desktop.
resvg-js blob demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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