Created
January 30, 2020 16:40
-
-
Save ArunMichaelDsouza/c51cec36058f6142f032c3f4c5af0c50 to your computer and use it in GitHub Desktop.
Rendering HTML on the canvas as an SVG image blob.
This file contains hidden or 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
| 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; |
Author
somehow, the img.onload = () => { } never runs properly even though it should i never get any console logs... and it will always give me null meaning it doestn run in my code.
@andrewwhiteingale just double checking - do you have a matching canvas tag in your HTML file to target?
<html>
<body>
<canvas></canvas>
<script>
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;
</script>
</body>
</html>yes I fixed the problem i had to put stuff in the bracket but there is another entirely different problem here. cough cough and i also missed the quatations
using foreignObject enables some browser security protocol and stuff for chromium
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
somehow, the img.onload = () => { } never runs properly
even though it should i never get any console logs... and it will always give me null meaning it doestn run in my code.