HTML | canvas measureText() Method

The measureText() method is used to return an object that represents the width of the specified text in terms of pixels. This method can be used to get the width of the text before writing it on canvas.

Syntax:

context.measureText(text).width;

Parameters:



  • text: This parameter specifies the text to be measured.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        HTML canvas measureText() Method
    </title>
</head>
  
<body style="text-align:left;">
  
    <h1>GeeksforGeeks</h1>
  
    <h2>HTML canvas measureText() Method</h2>
  
    <canvas id="GFG" width="500" height="200" style="border:2px solid">
    </canvas>
  
    <script>
        var doc_id = document.getElementById("GFG");
        var context = doc_id.getContext("2d");
        context.font = "30px solid";
        var txt = "GeeksforGeeks"
        context.fillText(txt, 180, 100);
        context.fillText("Width of GeeksforGeeks:" +
            context.measureText(txt).width, 0, 50);
    </script>
</body>
  
</html>

chevron_right


Output:

Supported Browsers: The browser supported by HTML canvas measureText() Method are listed below:

  • Google Chrome
  • Internet Explorer 9.0
  • Firefox
  • Safari
  • Opera


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.