English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The measureText() method returns information about the TextMetrics object containing the measured text (such as its width).
Before writing text on the canvas, please check the width of the text:
<!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 ‹/›
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.
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 | Description |
---|---|
text | Text to be measured. |