HTML5 Canvas Reference - measureText()








The measureText() method checks the text and returns an object that contains its width, in pixels.

Browser compatibility

measureText() Yes Yes Yes Yes Yes

JavaScript syntax

context.measureText(text).width;

Parameter Values

Parameter Description
text The text to measure




Example

The following code checks the width of text and outputs the result on canvas.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="150"></canvas>
<script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.font = "30px Arial";
    var txt = "Hello World"
    ctx.fillText(ctx.measureText(txt).width+"", 10, 100);
</script><!--from  ww w. j  a v  a 2 s  .  co  m-->
</body>
</html>

The code above is rendered as follows:





Example 2

The following code uses the measurement from the measureText to draw text.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="150"></canvas>
<script>
    var c = document.getElementById("myCanvas");
    var context = c.getContext("2d"); 
    context.font = "italic small-caps bold 44pt 'Comic Sans MS'"; 
     <!--from   w  w w . j  a v  a  2  s. c om-->
    context.strokeText("Hello", 10, 100); 
    context.fillText("World!", 10 + context.measureText("Hello ").width, 100); 

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

The code above is rendered as follows: