Skip to content

Instantly share code, notes, and snippets.

@ArunMichaelDsouza
Created January 30, 2020 16:40
Show Gist options
  • Save ArunMichaelDsouza/c51cec36058f6142f032c3f4c5af0c50 to your computer and use it in GitHub Desktop.
Save ArunMichaelDsouza/c51cec36058f6142f032c3f4c5af0c50 to your computer and use it in GitHub Desktop.
Rendering HTML on the canvas as an SVG image blob.
const data = `
<svg xmlns="http://www.w3.org/2000/svg">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml" style="border: 2px solid red; padding: 20px;">
<span style="font-size: 22px;">This will be rendered on the canvas.</span>
</div>
</foreignObject>
</svg>
`;
const svg = new Blob([data], { type: 'image/svg+xml;charset=utf-8' });
const url = window.URL.createObjectURL(svg);
const img = document.createElement('img');
img.onload = () => {
const ctx = document.querySelector('canvas').getContext('2d')
ctx.drawImage(img, 0, 0);
window.URL.revokeObjectURL(url);
}
img.src = url;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment