3

Given a string of any length in any font (not necessarily monospace, preferably Arial) I need a way to find the font size that will make the text fit perfectly into a specific pixel width, say 500 for example.

I'd MUCH prefer if there were a way to do this without using any libraries, CSS, or html. Pure JavaScript.

Thanks in advance!


P.S. I've heard of ctx.measureText(string).width but I couldn't figure out if it was helpful or not...

Spider53
  • 31
  • 5
  • 1
    What have you tried so far? – Kosh Jun 25 '18 at 22:38
  • I tried taking the pixel width and dividing by string.length. However that obviously only works with mono-space fonts. – Spider53 Jun 25 '18 at 22:46
  • Maybe this https://stackoverflow.com/a/25467363/1819684? – gforce301 Jun 26 '18 at 01:08
  • 1
    Thanks for that! Using the information I found from that link I was able to construct my own function that solves this problem: `getFontSize = function(text, targetWidth, font){ var size = 1; ctx.font = size + 'px ' + font; while(ctx.measureText(text).width < targetWidth){ size++; ctx.font = size + 'px ' + font; } return size; }` – Spider53 Jun 26 '18 at 17:02

0 Answers0