Skip to content

Instantly share code, notes, and snippets.

@alpha-and-omega
Created January 26, 2018 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alpha-and-omega/2bafcc5ef77e81d3fd45ee82d2b5a236 to your computer and use it in GitHub Desktop.
Save alpha-and-omega/2bafcc5ef77e81d3fd45ee82d2b5a236 to your computer and use it in GitHub Desktop.
fixes bug in textFit
From 6c3bc2d4881af2f0c2df92945e8ab18f2f07f52c Mon Sep 17 00:00:00 2001
From: alpha-and-omega <shivaa@mail.ru>
Date: Sun, 21 Jan 2018 17:06:50 +0300
Subject: [PATCH] fixes bug in binary search algorithm
---
textFit.js | 14 ++++++++------
1 file changed, 8 insertions(+), 6 deletions(-)
diff --git a/textFit.js b/textFit.js
index bd48d48..fae0052 100644
--- a/textFit.js
+++ b/textFit.js
@@ -148,21 +148,23 @@
el.style['white-space'] = 'nowrap';
}
- low = settings.minFontSize + 1;
- high = settings.maxFontSize + 1;
+ low = settings.minFontSize;
+ high = settings.maxFontSize;
- // Binary search for best fit
+ // Binary search for highest best fit
+ var size = low;
while (low <= high) {
- mid = parseInt((low + high) / 2, 10);
+ mid = (high + low) >> 1;
innerSpan.style.fontSize = mid + 'px';
if(innerSpan.scrollWidth <= originalWidth && (settings.widthOnly || innerSpan.scrollHeight <= originalHeight)){
+ size = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
- // Sub 1 at the very end, this is closer to what we wanted.
- innerSpan.style.fontSize = (mid - 1) + 'px';
+ // found, updating font if differs:
+ if( innerSpan.style.fontSize != size + 'px' ) innerSpan.style.fontSize = size + 'px';
// Our height is finalized. If we are aligning vertically, set that up.
if (settings.alignVert) {
--
2.14.2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment