Den*_*ret 18
没有标准功能.
因为我需要一个,我做了这个小函数来计算最合适的字符串:
function fittingString(c, str, maxWidth) {
var width = c.measureText(str).width;
var ellipsis = '…';
var ellipsisWidth = c.measureText(ellipsis).width;
if (width<=maxWidth || width<=ellipsisWidth) {
return str;
} else {
var len = str.length;
while (width>=maxWidth-ellipsisWidth && len-->0) {
str = str.substring(0, len);
width = c.measureText(str).width;
}
return str+ellipsis;
}
}
Run Code Online (Sandbox Code Playgroud)
c
2D上下文在哪里.
在设置了画布的字体和其他绘图参数后,您可以正常绘制字符串:
c.fillText(fittingString(c, "A big string that will likely be truncated", 100), 50, 50);
Run Code Online (Sandbox Code Playgroud)
在处理大量文本时,投票最高的答案会导致性能问题。
\n这是使用二分搜索来加速搜索正确长度的字符串的改编版本。
\nconst binarySearch = ({ max, getValue, match }) => {\n let min = 0;\n\n while (min <= max) {\n let guess = Math.floor((min + max) / 2);\n const compareVal = getValue(guess);\n\n if (compareVal === match) return guess;\n if (compareVal < match) min = guess + 1;\n else max = guess - 1;\n }\n\n return max;\n};\n\nconst fitString = (\n ctx,\n str,\n maxWidth,\n) => {\n let width = ctx.measureText(str).width;\n const ellipsis = '\xe2\x80\xa6';\n const ellipsisWidth = ctx.measureText(ellipsis).width;\n if (width <= maxWidth || width <= ellipsisWidth) {\n return str;\n }\n\n const index = binarySearch({\n max: str.length,\n getValue: guess => ctx.measureText(str.substring(0, guess)).width,\n match: maxWidth - ellipsisWidth,\n });\n\n return str.substring(0, index) + ellipsis;\n};\n
Run Code Online (Sandbox Code Playgroud)\n
小智 -2
html5的drawText没有这样的东西,实现起来会有点复杂。您需要用环来修剪绳子,直到适合所需的尺寸。如果文本没有旋转或有任何其他特殊效果,我建议使用具有绝对位置的普通 div 和以下 CSS 样式:
overflow: hidden;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
white-space: nowrap;
width: 100%;
Run Code Online (Sandbox Code Playgroud)