How to use HTML5 Canvas Text Metrics

This article describe about HTML5 Canvas Text metrics.
  • 3168

HTML5 Canvas Text Metrics

  • Text metrics is use mesaureText() method.
  • mesaureText() method requires a text string in HTML5.
  • mesaureText() method is return a object, mesaureText() is available text and text font to be the context.
  • So text baseline set following values in HTML5: top, middle, hanging, alphabetic, ideographic, and bottom.

Syntax

<script>
      var metrics = context.measureText('measure me!');
      var width = metrics.width;
</script>

Example

<!DOCTYPE HTML>

<html>

  <head>

    <style>

      body

 {

        margin: 0px;

        padding: 0px;

      }

      #myCanvas

 {

        border: 1px solid #9C9898;

      }

    </style>

    <script>

        window.onload = function ()

{

            var canvas = document.getElementById("myCanvas");

            var context = canvas.getContext("2d");

            var x = canvas.width / 2;

            var y = canvas.height / 2 - 10;

            var text = "I am canvas!";

 

            context.font = "30pt Calibri";

            context.textAlign = "center";

            context.fillStyle = "red";

            context.fillText(text, x, y);

 

            // get text metrics

            var metrics = context.measureText(text);

            var width = metrics.width;

            context.font = "20pt Calibri";

            context.textAlign = "center";

            context.fillStyle = "#555";

            context.fillText("(" + width + "px wide)", x, y + 40);

        };

 

    </script>

  </head>

  <body>

    <canvas id="myCanvas" width="400" height="170"></canvas>

  </body>

</html>

 

Output

You may also want to read these related articles here

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2019 DotNetHeaven. All rights reserved.