Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

HTML canvas measureText() method

HTML canvas measureText() method

Canvas Object Reference Canvas object

Example

Before outputting text on the canvas, check the width of the font:

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 »


Browser support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

Internet Explorer 9, Firefox, Opera, Chrome and Safari support the measureText() method.

**Note:** Internet Explorer 8 and earlier versions do not support .


Definition and Usage

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

**Tip:** If you need to know the width of the text before it is output to the canvas, use this method.

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

Parameter value

Parameters Description
text The text to measure.

Canvas Object Reference Canvas object