Skip to content

简易限制文字宽度的函数

英文外算两个字符宽度,可用于 canvas 绘制文字,文字超出部分隐藏或显示…

若精度要求比较高建议使用 ctx.measureText('text').width 去计算

ts
export function textOverflow(text: string, max: number, overflow: string = '…') {
  const s = /[\x00-\x7F]/;
  const toArray = (t: string) => [...t].map(it => (s.test(it) ? [it] : ['', it])).reduce((a, b) => a.concat(b), []);
  const texts: string[] = toArray(text);
  if (texts.length <= max) return texts.join('');
  return texts.slice(0, max - toArray(overflow).length).join('') + overflow;
}

textOverflow('你好,世界!', 10); // 你好,世…
textOverflow('12345', 4); // 12…
textOverflow('12345', 5); // 12345