Skip to content

Instantly share code, notes, and snippets.

@boyswan
Created February 18, 2023 18:17
Show Gist options
  • Save boyswan/fbc015e5056f3afc3834b0fb598207b9 to your computer and use it in GitHub Desktop.
Save boyswan/fbc015e5056f3afc3834b0fb598207b9 to your computer and use it in GitHub Desktop.
svg2canvas
// Example of svg -> b64
function svgTob64(svg_str) {
return "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svg_str)));
}
const get_image = b64 =>
new Promise((res, rej) => {
var img = new Image();
img.addEventListener("load", () => res(img));
img.addEventListener("error", (e) => rej(e.message));
img.setAttribute("src", b64);
});
const useSvgToCanvas = b64s => {
let [ready, set_ready] = React.useState(false);
let ref = React.useRef(null);
React.useEffect(() => {
let fn = async () => {
try {
let canvas = ref.current;
let ctx = canvas.getContext("2d");
canvas.width = 1024;
canvas.height = 1024;
for (let b64 of b64s) {
let img = await get_image(b64);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
}
set_ready((_) => true);
} catch (e) {
console.log("Image render error");
}
};
if (!!ref.current && b64s?.length) {
fn();
}
}, [b64s?.length]);
return [ref, ready];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment