Skip to content

Instantly share code, notes, and snippets.

@TotooriaHyperion
Last active December 11, 2019 09:03
Show Gist options
  • Save TotooriaHyperion/e29f48f479ac5b85d6325cd099cb3cb2 to your computer and use it in GitHub Desktop.
Save TotooriaHyperion/e29f48f479ac5b85d6325cd099cb3cb2 to your computer and use it in GitHub Desktop.
pixijs wordWrap and ellipse, support Asian charactors(breakWord = true)
export default function textEllipse(
text: string,
style: ConstructorParameters<typeof TextStyle>[0],
maxLines: number = Infinity,
) {
if (maxLines === Infinity) {
return text;
}
const { wordWrapWidth = 750, breakWords } = style!;
const pixiStyle = new TextStyle(style);
const { lines } = TextMetrics.measureText(text, pixiStyle);
let newText = text;
const spliter = breakWords ? "" : " ";
if (lines.length > maxLines) {
const truncatedLines = lines.slice(0, maxLines);
const lastLine = truncatedLines[truncatedLines.length - 1];
const words = lastLine.split(spliter);
const toMeasure = `${spliter}\n...\n${words.join("\n")}`;
const wordMetrics = TextMetrics.measureText(toMeasure, pixiStyle);
const [spliterLength, dotsLength, ...wordLengths] = wordMetrics.lineWidths;
const { text: newLastLine } = wordLengths.reduce(
(data, wordLength, i) => {
if (data.length + wordLength + spliterLength >= wordWrapWidth) {
return { ...data, length: wordWrapWidth };
}
return {
text: `${data.text}${i > 0 ? spliter : ""}${words[i]}`,
length: data.length + wordLength + spliterLength,
};
},
{ text: "", length: dotsLength },
);
truncatedLines[truncatedLines.length - 1] = `${newLastLine}...`;
newText = truncatedLines.join("\n");
}
return newText;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment