Skip to content

Instantly share code, notes, and snippets.

@andremichelle
Last active March 21, 2024 06:07
Show Gist options
  • Save andremichelle/28d4c5215d809726019077b6d02e2a5e to your computer and use it in GitHub Desktop.
Save andremichelle/28d4c5215d809726019077b6d02e2a5e to your computer and use it in GitHub Desktop.
Truncates the incoming text untill it fits into maxWidth
// 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