How to get the bounding box of a text using html5 canvas?

I found the answer before I submited the question:

http://mudcu.be/journal/2011/01/html5-typographic-metrics/#bboxUnicode http://www.w3schools.com/tags/canvas_measuretext.asp

var text_width = ctx.measureText("some text").width;

I used line height for text_height.

This gives not exact bounding box, but it is fast and usable before text rendering.


Works in Chrome:

const can = document.querySelector('canvas');
const ctx = can.getContext('2d');

let x = 10, y = 50;
let msg = "Hello, World!";

ctx.font = "30px monospace";

let textMetrics = ctx.measureText(msg);

ctx.fillText(msg, x, y);

console.log(textMetrics);

ctx.beginPath();
ctx.moveTo(
	x - textMetrics.actualBoundingBoxLeft,
  y - textMetrics.actualBoundingBoxAscent
);
ctx.lineTo(
  x + textMetrics.actualBoundingBoxRight, 
  y - textMetrics.actualBoundingBoxAscent
);
ctx.lineTo(
  x + textMetrics.actualBoundingBoxRight, 
  y + textMetrics.actualBoundingBoxDescent
);
ctx.lineTo(
	x - textMetrics.actualBoundingBoxLeft,
  y + textMetrics.actualBoundingBoxDescent
);
ctx.closePath();
ctx.stroke();
canvas {
  border: 1px solid black;
}
<canvas></canvas>

Tags:

Html

Canvas