Created
October 20, 2025 21:14
-
-
Save vytskalt/7f4c4d1a81ea300256b251146f9784d9 to your computer and use it in GitHub Desktop.
Rich text rendering on HTML canvas by abusing SVG foreignObject
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
| <!DOCTYPE html> | |
| <html> | |
| <body> | |
| <canvas id="canvas" width="512" height="512"></canvas> | |
| </body> | |
| <script> | |
| /** @type {HTMLCanvasElement} */ | |
| const canvas = window.canvas; | |
| const svgString = ` | |
| <svg width="512" height="512" xmlns="http://www.w3.org/2000/svg"> | |
| <foreignObject x="0" y="0" width="512" height="512"> | |
| <div xmlns="http://www.w3.org/1999/xhtml"> | |
| <span style="font-family: Arial, sans-serif; font-size: 32px; color: #333;"> | |
| <b>Rich</b> <span style="color: red">text</span> <i>rendering</i> <ins>on</ins> <em>HTML</em> <mark>canvas!</mark> | |
| </span> | |
| </div> | |
| </foreignObject> | |
| </svg> | |
| `; | |
| const svgBlob = new Blob([svgString], { type: 'image/svg+xml' }); | |
| const url = URL.createObjectURL(svgBlob); | |
| const ctx = canvas.getContext('2d'); | |
| const img = new Image(); | |
| img.onload = function() { | |
| ctx.drawImage(img, 50, 100); | |
| URL.revokeObjectURL(url); | |
| }; | |
| img.src = url; | |
| </script> | |
| <style> | |
| canvas { | |
| border: dashed red; | |
| } | |
| </style> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment