2023-07-07 17:40:59 -06:00

24 lines
704 B
TypeScript

import { CanvasRenderingContext2D } from "https://deno.land/x/skia_canvas@0.4.1/mod.ts";
export const wordWrap = (ctx: CanvasRenderingContext2D, text: string, maxWidth: number, lineWidth?: number) => {
const words = text.split(' ');
let testLine = '';
const lines: string[] = [];
for (const word of words) {
const previous = testLine;
testLine += ` ${word}`;
testLine = testLine.replace(/^\s/, '');
const { width } = ctx.measureText(testLine);
const calcedWidth = lineWidth && lines.length === 0 ? lineWidth : maxWidth;
if (width > calcedWidth) {
lines.push(previous);
testLine = word;
}
}
if (testLine) lines.push(testLine);
return lines;
}