THE WORLD'S LARGEST WEB DEVELOPER SITE

HTML canvas measureText() Method

❮ Canvas Object

Example

Check the width of the text, before writing it on the canvas:

YourbrowserdoesnotsupporttheHTML5canvastag.

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 »

Browser Support

The numbers in the table specify the first browser version that fully supports the method.

Method
measureText() 4.0 9.0 3.6 4.0 10.1

Definition and Usage

The measureText() method returns an object that contains the width of the specified text, in pixels.

Tip: Use this method if you need to know the width of a text, before writing it on the canvas.

JavaScript syntax: context.measureText(text).width;

Parameter Values

Parameter Description Play it
text The text to be measured Play it »

❮ Canvas Object