measureText method

Returns a CanvasTextMetrics object that contains the width of the specified text.

HTML Canvas 2D Context, Section 11



var retval = CanvasRenderingContext2D.measureText(text);


text [in]

Type: string

The text to measure.

Return value

Type: ICanvasTextMetrics

The width of the text, in CSS pixels.

Standards information


To get accurate measurements across different browsers, set the font and styles for text before getting your measurement. Measurements might still differ between browsers.


This example shows how to get the width value of a string using measureText. It displays the string before and after styling it, as well as the width in whole pixels. The parseInt() method is used to round to a whole number, as some browsers return the value as a floating point number.

<!DOCTYPE html>
    <title>MeasureText example</title>
  <canvas id="mycanvas" width="500" height="100"></canvas>
  <div id="mydiv"></div>  

  <script type="text/javascript">
    var myDiv = document.getElementById("mydiv");
    var canvas = document.getElementById("mycanvas");
    var context = canvas.getContext("2d");
    var text, textWidth;
    var message = [];

    // if supported, do the measurement
    if (context) {
      text = "This is a test sentence.";
      context.strokeText(text, 10, 20); // write test using default font

      // Get width using default value of font 
      textWidth = parseInt(context.measureText(text).width);
      message.push("Default: " + textWidth); 

      // Set the font properties
      context.font = "italic 200 36px Unknown Font, sans-serif";
      context.strokeStyle = "blue";

      // Write out the styled string
      context.strokeText(text, 10, 80);

      // And get the width of the string in the current font
      textWidth = parseInt(context.measureText(text).width);
      message.push("Style & Font set: " + textWidth);

      // Modify div with updated message
      myDiv.innerHTML = message.join("<br/>");
    } else {
      myDiv.innerHTML = "Canvas context not supported";


See also




© 2017 Microsoft