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 −

HTML Canvas MeasureText Method

HTML Canvas MeasureText Method

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 −

HTML Canvas MeasureText Method

HTML Canvas MeasureText Method
html_canvas_text.htm
Advertisements