Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 634
omega Avatar asked Aug 24 '12 16:08

omega


1 Answers

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();
}
like image 78
pimvdb Avatar answered Oct 06 '22 22:10

pimvdb