Last active
September 4, 2025 18:25
-
-
Save softmarshmallow/16bd6f4efafd5c71ecd94de73649c73b to your computer and use it in GitHub Desktop.
this demonstrates renders texts "without" rounding hack for its layout width.
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 lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <title>Text Width Demo</title> | |
| <style> | |
| body { | |
| font-family: Arial, sans-serif; | |
| font-size: 16px; | |
| } | |
| #text { | |
| display: inline-block; | |
| background: #eef; | |
| padding: 4px; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div id="text">Hello</div> | |
| <script> | |
| const el = document.getElementById("text"); | |
| const rect = el.getBoundingClientRect(); | |
| console.log("getBoundingClientRect width:", rect.width); | |
| const canvas = document.createElement("canvas"); | |
| const ctx = canvas.getContext("2d"); | |
| ctx.font = "16px Arial"; | |
| const metrics = ctx.measureText("Hello"); | |
| console.log("canvas.measureText width:", metrics.width); | |
| // Display them in the page too | |
| document.body.insertAdjacentHTML("beforeend", ` | |
| <p>Bounding rect width: ${rect.width}</p> | |
| <p>Canvas measureText width: ${metrics.width}</p> | |
| `); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment