Export (0) Print
Expand All

measureText method

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

HTML Canvas 2D Context, Section 11Internet Explorer 9

Syntax

var retval = CanvasRenderingContext2D.measureText(text);

Parameters

text [in]

Type: string

The text to measure.

Return value

Type: ICanvasTextMetrics

The width of the text, in CSS pixels.

Standards information

Remarks

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

Examples

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>
<html>
<head>    
    <title>MeasureText example</title>
</head>
<body>
  <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";
    }

  </script>
</body>
</html>



See also

CanvasRenderingContext2D

 

 

Show:
© 2014 Microsoft