javascript - 为什么每个项目的总宽度不等于画布文本度量中的总和
问题描述
字符宽度1
为 8.8984375。
所以我认为10个字符的宽度是88.984375,但实际上是78.296875。
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
ctx.font = '16px/16px arial';
let per = ctx.measureText('1').width;
let num = 10;
let total = ctx.measureText('1111111111').width;
console.log(per, total, per * 10);
<canvas id="canvas"></canvas>
解决方案
文本度量很复杂,尤其是当字体不是等距时。有些字符在单独测量时会被填充。1
使用时恰好是其中之一"arial"
计算填充。
假设
靠近其自身(任一侧)的字符将占用相同的宽度
每端的相同字符的字符串将具有相同的填充。
计算
对于字符“1”,我们可以通过测量 2 个案例“111”和“11111”来锻炼近似填充。然后我们可以创建一个表达式来定义字符宽度w
和填充p
。
因此对于字符串...
"111" 宽度为
w * 3 + p = w3
, 和“11111”宽度为
w * 5 + p = w5
.
我们现在有两个方程,我们可以得到w3
并w5
使用2 个未知数measureText
。
求解 p(填充)p = (15 * (w3 / 3) - (3 * w5)) / 2
然后 w(字符宽度)为w = (w3 - p) / 3
例子
该示例计算 1 的宽度,介于 1 和 1 到约 100 像素宽度之间。
const width = str => ctx.measureText(str).width;
const test = (str, calc) =>
console.log("'" + str + "' width = " + width(str).toFixed(2) +
"px, calculated = " + calc.toFixed(2) +
"px, dif = " + (calc - width(str)).toFixed(2) + "px");
const ctx = canvas.getContext("2d");
ctx.font = '16px arial';
const c = "1";
// calculate padding and width of 1
const w3 = width(c.padStart(3, c));
const w5 = width(c.padStart(5, c));
const padding = (15 * (w3 / 3) - 3 * w5) / 2;
const w = (w3 - padding) / 3;
// test result
test(c, w + padding);
test(c.padStart(10, c), w * 10 + padding);
test(c.padStart(20, c), w * 20 + padding);
console.log("Width of '"+c+"' is ~" + w.toFixed(2) + "px");
console.log("Padding is ~" + padding.toFixed(2) + "px");
<canvas id="canvas"></canvas>
其他角色
并非所有字符都有填充,下面的示例计算数字和小写字母的填充。
const width = str => ctx.measureText(str).width;
const test = (str, calc) =>
console.log("'" + str + "' width = " + width(str).toFixed(2) +
"px, calculated = " + calc.toFixed(2) +
"px, dif = " + (calc - width(str)).toFixed(2) + "px");
const ctx = canvas.getContext("2d");
ctx.font = '16px arial';
console.log("Font: " + ctx.font);
[..."1234567890abcdefghijklmnopqrstuvwxyz"].forEach(calcWidthFor);
function calcWidthFor(c) {
const w3 = width(c.padStart(3, c));
const padding = (15 * (w3 / 3) - (3 * width(c.padStart(5, c)))) / 2;
const w = (w3 - padding) / 3;
console.log("Width of '"+c+"' is ~ " + w.toFixed(2) + "px Padding is ~ " + padding.toFixed(2) + "px");
}
<canvas id="canvas"></canvas>
推荐阅读
- sql - 对多行的 JSON 属性求和
- google-sheets - 如何将一个单元格的文本插入另一个单元格?
- c++ - OpenCV 中的 cv::imread() 没有读取我的 .png
- python - 交叉验证和分数
- node.js - 在 NodeJS Glob 中排除具有特定前缀的子目录
- html - 带有祖父母的敲除/剪切文本效果
- php - 不能让它在我的代码上工作我不知道为什么,我收到以下错误:下面
- docusignapi - DocuSign API - 响应式签名
- node.js - React 应用程序可以同时与 Flask 通信并表达后端吗?
- timer - 在 P5js 中使用计时器固定距离画笔