A 10x faster and more accurate text wrapping util in < 2KB (min) (MIT Licensed)
uWrap exists to efficiently predict varying row heights for list and grid virtualization, a technique for UI performance optimization when rendering large, scrollable datasets.
Doing this both quickly and accurately turns out to be a non-trivial task since Canvas2D provides no API for text wrapping, and measureText()
is quite expensive;
measuring via DOM is also a non-starter due to poor performance.
Additionally, font size, variable-width fonts, letter-spacing
, explicit line breaks, and different white-space
choices affect the number of wrapped lines.
Notes:
- Today, works most accurately with Latin charsets
- Does not yet handle Windows-style
\r\n
explicit line breaks - Only
pre-line
wrapping strategy is implemented so far
uWrap handily out-performs canvas-hypertxt in both CPU and memory usage by a wide margin while being significantly more accurate.
The benchmark below wraps 100,000 random sentences in boxes of random widths between 50px and 250px. You can see this live in DevTools console of the demo page.
or
<script src="./dist/uWrap.iife.min.js"></script>
A 10 LoC uWrap.d.ts TypeScript def.
// import util for wrapping variable-width fonts using pre-line strategy
import { varPreLine } from 'uwrap';
// create a Canvas2D context with desired font settings
let ctx = document.createElement('canvas').getContext('2d');
ctx.font = "14px Inter, sans-serif";
ctx.letterSpacing = '0.15px';
// init util fns
const { count, test, split } = varPreLine(ctx);
// example text
let text = 'The quick brown fox jumps over the lazy dog.';
// count lines
let numLines = count(text, width);
// test if text will wrap
let willWrap = test(text, width);
// split lines (with optional limit)
let lines = split(text, width, 3);