Check text metrics on the HTML5 canvas

Example of how you can check the text metrics on the HTML5 canvas.

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="600" height="300"></canvas>
    <script>

    var text = 'Hello Tizen';

    var canvas = document.getElementById('myCanvas'); 
    var ctx = canvas.getContext('2d'); 
    
    ctx.font = '50pt Arial Black';
    ctx.textBaseline = 'middle'; // top, hanging, middle, alphabetic, ideographic, bottom 
    ctx.fillText(text, 150, 100);

    var textMetrics = ctx.measureText(text);
    var width = textMetrics.width;

        console.log("The text width is " + width + " pixels.");
       
   </script>
  </body>
</html>      

Responses

0 Replies