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 drawn on the canvas, please use this method.

Example

Check the font width before drawing text on the canvas:

Your browser does not support the HTML5 canvas tag.

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);

try it yourself

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.