Skip to content

Instantly share code, notes, and snippets.

@greggman
Last active January 28, 2026 05:29
Show Gist options
  • Select an option

  • Save greggman/6201ac4f48265ec6a3c7acdaafef66fd to your computer and use it in GitHub Desktop.

Select an option

Save greggman/6201ac4f48265ec6a3c7acdaafef66fd to your computer and use it in GitHub Desktop.
Canvas2D text metricsd do not work at small scales in Chrome

Canvas2D text metricsd do not work at small scales in Chrome

view on jsgist

/*bug-in-github-api-content-can-not-be-empty*/
<canvas width="64" height="64"></canvas>
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);
{"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