Page 1 of 1

Drawing text in Canvas to fit a Maximum line width

Posted: 31 Jan 2015, 09:22
by PloMar
Hi
I'm drawing text in an HTML5 canvas on top of an image. I want to calculate a font size so that the string will span 200 pixels width.
So basically, is there a way in JavaScript to determine what font size I should use for some string of a certain font for a given width?

Drawing text in Canvas to fit a Maximum line width

Posted: 31 Jan 2015, 09:59
by MarPlo
The fillText() method has an optional fourth argument, which is the max width to render the string.
- MDN's documentation says:
maxWidth - the maximum width to draw. If specified, and the string is computed to be wider than this width, the font is adjusted to use a more horizontally condensed font (if one is available or if a reasonably readable one can be synthesized by scaling the current font horizontally) or a smaller font.
Example:

Code: Select all

<canvas width="350" height="200" id="canvas"></canvas>
<script>
var ctx = document.getElementById('canvas').getContext('2d');

function drawTxt() {
  var w = 150;  // max-width of the text line
  ctx.font = "38px serif";
  ctx.fillText('Hello world', 10, 50, w);
}
drawTxt();
</script>
Demo: