Skip to content
Advertisement

Size to fit font on a canvas

I currently have this http://jsfiddle.net/dgAEY/ which works perfectly, I just need to figure out a way to size the font when it gets too long. I’ve looked into Auto-size dynamic text to fill fixed size container and I’ve tried to apply the Jquery function they posted but I couldn’t get it to work.

HTML

JavaScript

JavaScript

JavaScript

Advertisement

Answer

You can use context.measureText to get the pixel width of any given text in the current font.

Then if that width is too big, reduce the font size until it fits.

JavaScript

Demo:

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement