How to use HTML5 Canvas Text Metrics

This article describe about HTML5 Canvas Text metrics.
  • 3244

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.


      var metrics = context.measureText('measure me!');
      var width = metrics.width;








        margin: 0px;

        padding: 0px;




        border: 1px solid #9C9898;




        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);






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





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

© 2020 DotNetHeaven. All rights reserved.