HTML canvas measureText() Method
Definition and Usage
measureText()
The method returns an object that contains the specified font width in pixels.
Tip:If you need to know the width of the text before it is output to the canvas, please use this method.
Example
Before outputting text to the canvas, check the width of the font:
JavaScript:
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.font="30px Arial"; var txt="Hello World" ctx.fillText("width:" + ctx.measureText(txt).width,10,50) ctx.fillText(txt,10,100);
Syntax
context.measureText(text).width;
Parameter Value
Parameter | Description |
---|---|
text | The text to be measured. |
Browser Support
The numbers in the table indicate the first browser version that fully supports this property.
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
4.0 | 9.0 | 3.6 | 4.0 | 10.1 |
Note:Internet Explorer 8 and earlier versions do not support the <canvas> element.