user669677
user669677

Reputation:

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

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

Upvotes: 12

Views: 7511

Answers (3)

Dan
Dan

Reputation: 1

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

/* See w3schools box-sizing page */

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

Upvotes: -1

psqq
psqq

Reputation: 963

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>

Upvotes: 7

user669677
user669677

Reputation:

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.

Upvotes: 12

Related Questions