Drawing text in Canvas to fit a Maximum line width

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
PloMar
Posts: 48

Drawing text in Canvas to fit a Maximum line width

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?

MarPlo Posts: 186
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:

Similar Topics