Last active
January 28, 2026 05:29
-
-
Save greggman/6201ac4f48265ec6a3c7acdaafef66fd to your computer and use it in GitHub Desktop.
Canvas2D text metricsd do not work at small scales in Chrome
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
| /*bug-in-github-api-content-can-not-be-empty*/ |
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"></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 ctx = document.querySelector('canvas').getContext('2d'); | |
| ctx.fillStyle = 'red'; | |
| ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); | |
| function drawCenteredTextAtPoint(ctx, text, x, y) { | |
| const metrics = ctx.measureText(text); | |
| const drawX = x - (metrics.actualBoundingBoxLeft + metrics.actualBoundingBoxRight) / 2 + metrics.actualBoundingBoxLeft; | |
| const drawY = y + (metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent) / 2 - metrics.actualBoundingBoxDescent; | |
| ctx.save(); | |
| ctx.textAlign = "left"; | |
| ctx.textBaseline = "alphabetic"; | |
| ctx.fillText(text, drawX, drawY); | |
| ctx.restore(); | |
| } | |
| ctx.translate(32, 32); | |
| ctx.scale(32, 32); | |
| ctx.fillStyle = 'yellow'; | |
| ctx.font = '1.5px monospace'; | |
| drawCenteredTextAtPoint(ctx, '1x', 0, 0); |
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":"Canvas2D text metricsd do not work at small scales in Chrome","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