js 中英文字符以及标点符号宽度会有所不同,导致 canvas 无法直接用fontSize计算内容宽度,可以用以下方法获取文字的真实宽度。
const getLetterWidth = (letter, fontSize) => {
const dom = document.createElement('span');
dom.style.display = 'inline-block';
dom.style.fontSize = fontSize + 'px';
dom.textContent = letter;
document.body.appendChild(dom);
const width = dom.getBoundingClientRect().width;
dom.remove();
return Number(width.toFixed(2));
};
网友评论