# 已知html当中width 宽度和字体大小font-size ，如何计算一行大致能放几个字？

wanwanwan
• 193
``````                <td style="width:100pt;border-top-style:solid;border-top-width:1pt;border-left-style:solid;border-left-width:1pt;border-bottom-style:solid;border-bottom-width:1pt;border-right-style:solid;border-right-width:1pt" colspan="3">
<p class="font-size:11pt" style="padding-left: 84pt;text-indent: 0pt;line-height: 13pt;text-align: right;">
123
</p>
</td>``````

##### 4个回答

``````/**
* 更具容器宽度算出一行所能容纳的最大字数
* @param containerWidth 容器宽度
* @param char 用测算的字符
* @param font 字体
*/
const charCountFitInWith = (
containerWidth: number,
char: string = "国",
font: string = "11px Microsoft YaHei"
) => {
let left = 1;
/**
* 一行可容纳的最大字符数量，可根据业务进行调整，以减小迭代次数
*/
let right = 2 ** 16;
const canvasEle = document.createElement("canvas");
const context = canvasEle.getContext("2d");
context.font = font;

while (left <= right) {
const mid = Math.floor((left + right) / 2);

const str = char.repeat(mid);
const { width } = context.measureText(str);

if (width >= containerWidth) {
right = mid - 1;
} else {
left = mid + 1;
}
}

return left;
};

console.log(charCountFitInWith(112, "国")); //11
console.log(charCountFitInWith(10000, "赢")); //910
console.log(charCountFitInWith(10000, "a")); //1645
``````