在将 DOM 元素 (
position: absolut/fixed; display: block;
) 中的文本附加到文档之前,我会获取 TextMetrics,如下所示:
function getTextMetrics(txt, font) {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
context.font = font;
const tm = context.measureText(txt);
return tm;
}
看着
tm
我无法理解如何获得渲染的高度/宽度。似乎缺少了一些东西。什么?
是的,返回的 TextMetric 中有一些字段几乎适合,但它们不等于稍后渲染元素的 .clientWidth/Height。
无需为此创建“工作示例”。这太简单了。这里有一些数字(来自 Google Chrome,@ggorlen 提到的值在那里不存在):
.clientWidth: 82
.clientHeight: 20
tm:
width : 73.2734375
fontBoundingBoxAscent : 16
fontBoundingBoxDescent : 3
这是我过去用过的东西:
tm = context.measureText(txt); // width is obvious "tm.width"
h = tm.actualBoundingBoxAscent + tm.actualBoundingBoxDescent
尝试下面的代码,看看是否能让您更接近目标。
function fillText(ctx, x, y, txt, font) {
ctx.font = font;
ctx.fillText(txt, x, y)
const tm = context.measureText(txt);
const h = tm.actualBoundingBoxAscent + tm.actualBoundingBoxDescent
ctx.rect(x, y, tm.width, -h);
ctx.stroke();
return tm;
}
const canvas = document.getElementById("x");
const context = canvas.getContext("2d");
context.strokeStyle = "red";
x = fillText(context, 10, 30, "HELLO", "20px monospace")
//console.log(x)
x = fillText(context, 10, 85, "WORLD", "60px monospace")
//console.log(x)
x = fillText(context, 120, 35, "123.456-7890", "40px monospace")
//console.log(x)
<canvas id="x" width=600></canvas>