html tutorial - measureText() Method in HTML5 Canvas - html5 - html code - html form



Measuretext method in html5 canvas

Learn html - html tutorial - Measuretext method in html5 canvas - html examples - html programs

  • The measureText() method is used to set values that contains the width of the specified text, in pixels.

Syntax for measureText() Method in HTML5 Canvas:

context.measureText(text).width;

Parameter values for measureText() Method in HTML5 Canvas:

Parameter Description
text The text to be measured.

Sample Coding for measureText() Method in HTML5 Canvas:

Tryit<!DOCTYPE html>
<html>
    <head>
      <title>wikitechy-measureText() method in Canvas</title>
    </head>
    <body>
        <h2>Wikitechy-measureText() method in canvas</h2>
        <canvas id="wikitechyCanvas" width="300" height="150" 
          style="border:1px solid #d3d3d3;">
        </canvas>
        <script>
            var canvas = document.getElementById("wikitechyCanvas");
            var context = canvas.getContext("2d");
            context.font = "25px Times new Roman";
            var txt = "wikitechy world";
            context.fillText("width:" + context.measureText(txt).width, 10, 50);
            context.fillText(txt, 10, 100);
        </script>
    </body>
</html>

Code Explanation for measureText() Method in HTML5 Canvas:

measureText() method in HTML5 canvas Code Explanation

  1. ”wikitechyCanvas” is used to declare the id value of the canvas tag.
  2. getElementById: method is used to draw the element from canvas id value.
  3. The canvas.getContext() method returns an object that provides methods and properties for drawing on the canvas.
  4. The context.font method is used to set the font property as “25 px Times New Roman;
  5. The context.fillText() method is used to filltext(10,100).

Output for measureText() Method in HTML5 Canvas:

measureText() method in HTML5 canvas Output

  1. <canvas> is used to draw a rectangle and transform
  2. Defines a font style (25px times New Roman)

Browser Support for measureText() Method in HTML5 Canvas:

Yes 9.0 Yes Yes Yes

Related Searches to measureText() Method in HTML5 Canvas