omega
omega

Reputation: 43833

html5 canvas - How can I stretch text?

In my html 5 canvas, I draw text (that has to be on 1 line) but it needs to be a constant font size and style and the width of the space I have is also constant. Therefore the text needs to fit in that space, but the problem occurs when the text is too long and goes past the space.

So is there a way I can horizontally stretch/compress text? (like in PhotoShop)

Something like convert it to an image then change the width of the image? Not sure if this is the best way...

Thanks

Upvotes: 5

Views: 6209

Answers (2)

pimvdb
pimvdb

Reputation: 154818

You can use measureText to determine the size of the text first, then scale the canvas if needed: http://jsfiddle.net/eGjak/887/.

var text = "foo bar foo bar";
ctx.font = "30pt Arial";

var width = ctx.measureText(text).width;
if(width <= 100) {
    ctx.fillText(text, 0, 100);
} else {
    ctx.save();
    ctx.scale(100 / width, 1);
    ctx.fillText(text, 0, 100);
    ctx.restore();
}

Upvotes: 9

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

A simple solution is to draw your text in another (in memory) canvas and then use drawImage to paste the canvas content in the real destination canvas.

Something like this (let it be parameterizable depending on your needs, here stretching with a ratio of 100 to 80) :

var tempimg = document.createElement('canvas');
tempimg.width = 100;
tempimg.height = 10;
oc = tempimg.getContext('2d');
oc.fillText(...)
yourdestcontext.drawImage(tempimg, 0, 0, 100, 10, x, y, 80, 10);

Upvotes: 2

Related Questions