- HTML Canvas Tutorial
- HTML Canvas - Home
- HTML Canvas - Introduction
- Environmental Setup
- HTML Canvas - First Application
- HTML Canvas - Drawing 2D Shapes
- HTML Canvas - Path Elements
- 2D Shapes Using Path Elements
- HTML Canvas - Colors
- HTML Canvas - Adding Styles
- HTML Canvas - Adding Text
- HTML Canvas - Adding Images
- HTML Canvas - Canvas Clock
- HTML Canvas - Transformations
- Composting and Clipping
- HTML Canvas - Basic Animations
- Advanced Animations
- HTML Canvas API Functions
- HTML Canvas - Element
- HTML Canvas - Rectangles
- HTML Canvas - Lines
- HTML Canvas - Paths
- HTML Canvas - Text
- HTML Canvas - Colors and Styles
- HTML Canvas - Images
- HTML Canvas - Shadows and Transformations
- HTML Canvas Useful Resources
- HTML Canvas - Quick Guide
- HTML Canvas - Useful Resources
- HTML Canvas - Discussion
HTML Canvas - measureText() Method
The HTML Canvas measureText() method of Canvas API from the CanvasRenderingContext2D interface returns text width of the text drawn using context object from the Canvas element.
Syntax
Following is the syntax of HTML Canvas measureText() method −
CanvasRenderingContext2D.measureText(text);
Parameters
Following is the list of parameters of this method −
S.No | Parameters and Description |
---|---|
1 | text
The text string to be measured from the Canvas element. |
Return values
Upon calling this method by the context object, the text width is returned to the user by window alerts or console.
Example 1
The following example draws a text onto the canvas element using fillText() method and return its width by the console using HTML Canvas measureText() method.
<!DOCTYPE html> <html lang="en"> <head> <title>Reference API</title> <style> body { margin: 10px; padding: 10px; } </style> </head> <body> <canvas id="canvas" width="250" height="100" style="border: 1px solid black;"></canvas> <script> var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); context.font = '30px Verdana' context.fillText('Hello World', 20, 50); var text = context.measureText('Hello World'); console.log(text.width); </script> </body> </html>
Output
The output returned by the above code on the webpage as −
Example 2
The following example draws text and return its width from the Canvas element by window alert using measureText() method.
<!DOCTYPE html> <html lang="en"> <head> <title>Reference API</title> <style> body { margin: 10px; padding: 10px; } </style> </head> <body> <canvas id="canvas" width="250" height="100" style="border: 1px solid black;"></canvas> <script> var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); context.font = '30px Verdana' context.fillText('TutorialsPoint', 20, 50); var text = context.measureText('TutorialsPoint'); alert(text.width); </script> </body> </html>
Output
The output returned by the above code on the webpage as −
To Continue Learning Please Login
Login with Google