import { fromCodePoint, LineBreaker, toCodePoints } from 'css-line-break'; import './polyfill'; const wordSeparators = [ 0x0020, 0x00a0, 0x1361, 0x10100, 0x10101, 0x1039, 0x1091, ]; const breakWords = (str: string): string[] => { const breaker = LineBreaker(str, { lineBreak: 'normal', wordBreak: 'normal', }); const words = []; let bk; while (!(bk = breaker.next()).done) { if (bk.value) { const value = bk.value.slice(); const codePoints = toCodePoints(value); let word = ''; codePoints.forEach(codePoint => { if (wordSeparators.indexOf(codePoint) === -1) { word += fromCodePoint(codePoint); } else { if (word.length) { words.push(word); } words.push(fromCodePoint(codePoint)); word = ''; } }); if (word.length) { words.push(word); } } } return words; }; interface CharacterWidthCache { [key: string]: number; } const getFromCache = ( key: string, letterSpacing: number, cache: CharacterWidthCache, context: CanvasRenderingContext2D ): number => { let width = cache[key]; if (typeof width !== 'number') { const spacing = key.length * letterSpacing; width = context.measureText(key).width + spacing; cache[key] = width; } return width; }; const wordWrapFunc = ( text: string, context: CanvasRenderingContext2D, style: PIXI.TextStyle ) => { const { wordWrapWidth, letterSpacing = 0 } = style; const textWidthCache: CharacterWidthCache = {}; let output = ''; // Condense consecutive spaces and split into lines const lines = text.split(/(?:\r\n|\r|\n)/); const linesCount = lines.length; const getBigTextWidth = (wordsBig: string[]) => { const newBigWords = []; const newBigWidth = []; let currentBigLineWidth = 0; let outBig = ''; for (let c = 0; c < wordsBig.length; c++) { const t = wordsBig[c]; let w = textWidthCache[t]; if (typeof w === 'undefined') { w = getFromCache(t, letterSpacing, textWidthCache, context); // context.measureText(t).width; textWidthCache[t] = w; } if (w > wordWrapWidth && t.length > 1) { const tt = t.split(''); const dd: any = getBigTextWidth(tt); newBigWords.push(dd.newBigWords); newBigWidth.push(dd.newBigWidth); continue; } if ( currentBigLineWidth + w > wordWrapWidth && getFromCache(outBig + t, letterSpacing, textWidthCache, context) > wordWrapWidth // 单字与词语组合长度不一样,再加上单字做比较 ) { if (outBig) { newBigWords.push(outBig); newBigWidth.push(currentBigLineWidth); } outBig = t; currentBigLineWidth = w; } else { currentBigLineWidth += w; outBig += t; } if (c >= wordsBig.length - 1) { if (outBig) { newBigWords.push(outBig); newBigWidth.push(currentBigLineWidth); } outBig = ''; currentBigLineWidth = 0; } } return { newBigWords, newBigWidth, }; }; for (let len = 0; len < linesCount; len++) { const lineText = lines[len]; let words: any = breakWords(lineText); if (!words.length) { output += lineText + '\n'; continue; } let wordsWidthArray = words.map((word: any, i: number) => { let sW = 0; for (let ss = 0; ss < word.length; ss++) { const t = word[ss]; if (!textWidthCache[t]) { textWidthCache[t] = getFromCache( t, letterSpacing, textWidthCache, context ); } sW += textWidthCache[t]; } // console.log(word, sW, wordWrapWidth); if (sW > wordWrapWidth && word.length > 1) { const wordsBig = breakWords(words[i]); const { newBigWidth, newBigWords } = getBigTextWidth(wordsBig); words[i] = newBigWords; return newBigWidth; } return sW; }); words = words.flat(2); wordsWidthArray = wordsWidthArray.flat(2); let currentLineWidth = 0; let out = ''; for (let i = 0; i < wordsWidthArray.length; i++) { const wordWidth = wordsWidthArray[i]; // console.log(out, output, words[i], currentLineWidth, wordWidth); if (currentLineWidth + wordWidth > wordWrapWidth) { if (out) { output += out.replace(/[ \n]*$/gi, '') + '\n'; } out = words[i]; currentLineWidth = wordWidth; // 回行的第一个空格去掉 if (!words[i].trim()) { out = ''; currentLineWidth = 0; } } else { currentLineWidth += wordWidth; out += words[i]; } if (i >= wordsWidthArray.length - 1) { if (out) { output += out.replace(/[ \n]*$/gi, '') + '\n'; } out = ''; currentLineWidth = 0; } } } // Trim the end of the string output = output.replace(/\n$/gi, ''); return output; }; export function fixTextWordWrap(): void { /** * 换行规则 * 英文空格换行 * 中文字符换行,遇标点符号带上前个字符换行, */ PIXI.CanvasTextMetrics.measureText = function ( text: string, style: PIXI.TextStyle, canvas: any = PIXI.CanvasTextMetrics._canvas, wordWrap: boolean = style.wordWrap ): PIXI.CanvasTextMetrics { const textKey = `${text}-${style.styleKey}-wordWrap-${wordWrap}`; const measurementCache = // @ts-ignore PIXI.CanvasTextMetrics._measurementCache || new Map(); if (measurementCache.has(textKey)) { return measurementCache.get(textKey); } const { distance, blur } = style.dropShadow || { distance: 0, blur: 0 }; // style.padding = blur || 0; const font = PIXI.fontStringFromTextStyle(style); const fontProperties = PIXI.CanvasTextMetrics.measureFont(font); // fallback in case UA disallow canvas data extraction // (toDataURI, getImageData functions) if (fontProperties.fontSize === 0) { fontProperties.fontSize = style.fontSize as number; fontProperties.ascent = style.fontSize as number; } // @ts-ignore const context = PIXI.CanvasTextMetrics.__context; // canvas.getContext('2d')!; context.font = font; const outputText = wordWrap ? wordWrapFunc(text, context, style) : text; const lines = outputText.split(/(?:\r\n|\r|\n)/); const lineWidths = new Array(lines.length); let maxLineWidth = 0; for (let i = 0; i < lines.length; i++) { const lineWidth = context!.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing; lineWidths[i] = lineWidth; maxLineWidth = Math.max(maxLineWidth, lineWidth); } const strokeWidth = style._stroke?.width || 0; let width = maxLineWidth + strokeWidth + 1; // +1 避免文字输入框被截断 if (style.dropShadow) { width += distance + blur; } const lineHeight = style.lineHeight || fontProperties.fontSize + strokeWidth; let height = Math.max(lineHeight, fontProperties.fontSize + strokeWidth) + (lines.length - 1) * (lineHeight + style.leading); if (style.dropShadow) { height += distance + blur; } const measurements = new PIXI.CanvasTextMetrics( text, style, width, height, lines, lineWidths, lineHeight + style.leading, maxLineWidth, fontProperties ); measurementCache.set(textKey, measurements); return measurements; }; }