3

I need to 'scale' text to fill an antire HTML5 canvas. It appears that the scale() method does not affect text. I've seen approximation methods with iterative loops on the measureText() method but this doesn't get me exactly what I need. Ideally I'd like to fill both horizontally and vertically without conserving the aspect ratio. Would SVG possibly be able to help with this?

Neuron
  • 5,141
  • 5
  • 38
  • 59
Weezelboy
  • 117
  • 1
  • 2
  • 8
  • So, in case you have five characters and a canvas with a width of 19 pixels, you want your text to fill the entire canvas (not only 15px)? – thejh Nov 06 '10 at 16:50

2 Answers2

5

My bad - Scale DOES apply to text. I've come up with a solution:

context.font = "20px 'Segoe UI'";
var metrics = context.measureText("Testing!");
var textWidth = metrics.width;

var scalex = (canvas.width / textWidth);
var scaley = (canvas.height / 23);

var ypos = (canvas.height / (scaley * 1.25));

context.scale(scalex, scaley);
context.fillText("Testing!", 0, ypos);
Weezelboy
  • 117
  • 1
  • 2
  • 8
  • 1
    If you're running this in a loop, remember to `context.save()` before transformations, and `context.restore()` after (preferably in a finally block). – leviathanbadger Jul 14 '17 at 02:18
1

Scale does affect text. Try this:

var can = document.getElementById('test');
var ctx = can.getContext('2d');

ctx.fillText("test", 10, 10); // not scaled text


ctx.scale(3,3);
ctx.fillText("test", 10, 10); // scaled text

See it in action here: http://jsfiddle.net/3zeBk/8/

Neuron
  • 5,141
  • 5
  • 38
  • 59
Simon Sarris
  • 62,212
  • 13
  • 141
  • 171