leeoniya/uWrap
关于
A 10x faster and more accurate text wrapping util in < 2KB (min)
其他项目实测星标增长
- 24小时
- 0
- 7天
- 0
- 15天
- 0
- 1个月
- 正在收集历史
各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。
README.md
原文⏎ μWrap
A 10x faster and more accurate text wrapping util in < 2KB (min) (MIT Licensed)
Introduction
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 kerning, letter-spacing, explicit line breaks, and different white-space choices affect the wrapping locations.
Notes:
- Currently works most accurately with Latin charsets
- Does not yet handle Windows-style
\r\nexplicit line breaks - Only
pre-linewrapping strategy is implemented so far
Performance
uWrap outperforms canvas-hypertxt by a wide margin in both CPU and memory usage while being significantly more accurate.
The benchmark below wraps 100,000 random sentences into boxes of random widths between 50px and 250px. You can see this live in DevTools console of the demo page.
| Chrome 135 | Firefox 137 | Safari 18.1 | |
|---|---|---|---|
| uWrap | 82ms | 90ms | 185ms |
| canvas-hypertxt | 770ms | 1660ms | 1430ms |
Installation
npm i uwrap
or
<script src="./dist/uWrap.iife.min.js"></script>
API
See uWrap.d.ts TypeScript def.
Usage
// import fn 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);
探索相关项目
加载中…