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

I would like to get some text's bounding box.



Solution 1:[1]

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>

Solution 2:[2]

Maybe I don't understand the question, but what about:

/* See w3schools box-sizing page */

<style>
* {
    box-sizing: border-box;
} 
</style>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pank
Solution 2 Syscall