Sometimes, we want to find the height of text on an HTML canvas with JavaScript.
In this article, we’ll look at how to find the height of text on an HTML canvas with JavaScript.
How to find the height of text on an HTML canvas with JavaScript?
To find the height of text on an HTML canvas with JavaScript, we can use the canvas context’s measureText
method.
For instance, we write
const metrics = ctx.measureText(text);
const fontHeight =
metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent;
const actualHeight =
metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent;
to call measureText
on the ctx
canvas context.
We call it with the text
string to get the text
‘s dimensions.
And then we get the fontHeight
and actualHeight
with
metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent;
and
metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent;
Conclusion
To find the height of text on an HTML canvas with JavaScript, we can use the canvas context’s measureText
method.