Skip to main content
measureText method

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

HTML Canvas 2D Context, Section 11 Internet 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 canvas = document.getElementById("mycanvas");
    // if supported, do the measurement
    if (canvas.getContext) {
      var mytext = "This is a test sentence.";
      var ctx = canvas.getContext("2d"); 
      ctx.strokeText(mytext, 10, 20); // write test using default font
      // Get width using default value of font 
      document.getElementById("mydiv").innerHTML = "Default: " + parseInt(ctx.measureText(mytext).width);
      // Set the font properties for the current context
      ctx.font = "italic 200 36px Unknown Font, sans-serif";
      ctx.strokeStyle = "blue"; // set stroke color to blue
      // Write out the styled string
      ctx.strokeText(mytext, "10", "80");
      // And get the width of the string in the current font
      document.getElementById("mydiv").innerHTML += "<br/>Style & Font set: " + parseInt(ctx.measureText(mytext).width);
    } else {
      document.getElementById("mydiv").innerHTML = "Canvas context not supported";
    }
    
  </script>
</body>
</html>

See also

CanvasRenderingContext2D

 

 

Send comments about this topic to Microsoft

Build date: 11/28/2012