Canvas How to - Measure font size








Question

We would like to know how to measure font size.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--from  ww w  . ja  va 2 s. c o  m-->
var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d');
    var fontSizes = [72, 36, 28, 14, 12, 10, 5, 2],
    text = 'Measure me!';
    ctx.textBaseline = 'top';
    ctx.fillStyle = 'blue';
    var textDimensions,
    i = 0;
    do {
       ctx.font = fontSizes[i++] + 'px Arial';
       textDimensions = ctx.measureText(text);
    } while (textDimensions.width >= canvas.width);
    ctx.fillText(text, (canvas.width - textDimensions.width) / 2, 10);
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width="300" height="200" />
</body>
</html>

The code above is rendered as follows: