use-fit-text icon indicating copy to clipboard operation
use-fit-text copied to clipboard

We can get rid of the binary search in the font size algorithm

Open jt3k opened this issue 3 years ago • 2 comments

I read in the Readme that you are using binary search. It seems that performance can be improved by not using binary search.

The algorithm for finding the font size is as follows:

  1. get the width of the text const {width} = myElement. getBoundingClientRect();
  2. coefficient = element_width / fontSize
  3. to get the font size that will fit without breaking a line in a div with a width of 400 pixels, you need to divide 400 by this coefficient; newFontSize = 400 / coefficient
  4. ...
  5. Profit! :)

A working demo and code can be viewed here

and here you can look at this algorithm:

jt3k avatar Jun 01 '21 11:06 jt3k

@jt3k Such algorithm is nice but unfortunately imprecise. Text can overlap or be not as big as possible.

steida avatar Nov 07 '21 16:11 steida

I know this is an old issue, but did you have any examples of this algorithm breaking? In my testing it's working okay, but it sounds like the issues are tricky edge case.

oeed avatar Dec 19 '23 23:12 oeed