Last active
March 21, 2024 06:07
-
-
Save andremichelle/28d4c5215d809726019077b6d02e2a5e to your computer and use it in GitHub Desktop.
Truncates the incoming text untill it fits into maxWidth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Truncates the incoming text untill it fits into maxWidth | |
// Based on binary-search, hence only log(N) iterations | |
// | |
const findMaxFittingText = (context: CanvasRenderingContext2D, text: string, maxWidth: number): string => { | |
let l: number = 0 | |
let r: number = text.length | |
while (l < r) { | |
const mid: number = (r + l) >> 1 | |
const testString = text.substring(0, mid + 1) | |
if (Math.ceil(context.measureText(testString).width) <= maxWidth) { | |
l = mid + 1 | |
} else { | |
r = mid | |
} | |
} | |
return text.substring(0, l) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment