lowerkey
lowerkey

Reputation: 8325

How to find the dimensions of context.fillText(text, x, y)

I am drawing text on a canvas and was wondering how I can get the dimensions of the text to be drawn.

Height should be simple enough.

My only thought is that to use a monospace font, and calculate the length from the number of characters. Is there a better way to do this yet?

Upvotes: 1

Views: 803

Answers (1)

acm
acm

Reputation: 6637

Have you read this drawing text using canvas documentation? Especially from the methods section;
The measureText() method seems to do what you ask.

Although there is no example at the documentation I'm guessing the use is something like:

var text = 'this is my text';
var text_ctx = ctx.measureText(text);
var text_width = text_ctx.width;

Upvotes: 3

Related Questions