English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML reference manual

HTML tag list

HTML canvas measureText() method

The measureText() method returns information about the TextMetrics object containing the measured text (such as its width).

HTML canvas Reference Manual

Online example

Before writing text on the canvas, please check the width of the text:

Your browser does not support HTML5 canvas tag.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML canvas measureText() method usage-Basic tutorial(oldtoolbag.com)</<title>
</<head>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3">
Your browser does not support HTML5 canvas tag
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
var txt = "基础教程oldtoolbag.com"
ctx.fillText("width:") + ctx.measureText(txt).width, 10, 50)
ctx.fillText(txt, 10, 100);
</script>
</body>
</html>
Test to see ‹/›

Browser Compatibility

IEFirefoxOperaChromeSafari

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

Note:Internet Explorer 8 and earlier versions do not support the <canvas> element.

Definition and Usage

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

Tip:If you need to know the width of the text before outputting it to the canvas, please use this method.

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

Parameter Value

 
ParameterDescription
textText to be measured.
HTML canvas Reference Manual