Created
November 18, 2025 05:50
-
-
Save greggman/331c5868e801c0ba231ae04a18922758 to your computer and use it in GitHub Desktop.
Canvas 2D: drawElement with save
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
| html { font-family: monospace; font-size: 8px; background-color: #CCC;} | |
| canvas { border: 1px solid gray; } | |
| .test { background-color: red; color: yellow; font: initial; font-size: initial; } | |
| .test>div { | |
| border: 1px solid black; | |
| } | |
| .outer { display: inline-block; background-color: #EEE; margin: 0.5em; padding: 0.5em; } |
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
| <canvas width="64" height="64" layoutsubtree> | |
| <div class="test"> | |
| <div style="font-size: 16px;">ThisIsIntensionallySomethingThatIsTooLong</div> | |
| <div style="font-size: 12px;">ThisIsIntensionallySomethingThatIsTooLong</div> | |
| <div style="font-size: 10px;">ThisIsIntensionallySomethingThatIsTooLong</div> | |
| <div style="font-size: 8px;">ThisIsIntensionallySomethingThatIsTooLong</div> | |
| <div> | |
| </canvas> |
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 canvas = document.querySelector('canvas'); | |
| const ctx = canvas. getContext('2d'); | |
| const elem = ctx.canvas.firstElementChild; | |
| ctx.drawElement(elem, 0, 0); | |
| const saveBlob = (function() { | |
| const a = document.createElement('a'); | |
| document.body.appendChild(a); | |
| a.style.display = 'none'; | |
| return function saveData(blob, fileName) { | |
| const url = window.URL.createObjectURL(blob); | |
| a.href = url; | |
| a.download = fileName; | |
| a.click(); | |
| }; | |
| }()); | |
| canvas.toBlob((blob) => saveBlob(blob, 'canvas-64x64.png')); |
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
| {"name":"Canvas 2D: drawElement with save","settings":{},"filenames":["index.html","index.css","index.js"]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment