Chrome 从canvas.measureText获取包含元素的预期呈现大小?

utugiqy6  于 9个月前  发布在  Go
关注(0)|答案(1)|浏览(139)

在DOM元素(position: absolut/fixed; display: block;)附加到文档之前,我为它获取文本的文本,如下所示:

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

4si2a6ki

4si2a6ki1#

这是我过去用过的东西:

tm = context.measureText(txt); // width is obvious "tm.width" 
    h = tm.actualBoundingBoxAscent + tm.actualBoundingBoxDescent

字符串
.要明确的是,这些值是针对特定画布中的文本的,这些值与画布之外的其他元素没有直接关系。
从文档中:
https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics
TextData接口表示画布中一段文本的尺寸;可以使用CanvasRenderingContext2D.measureText()方法检索TextData示例。
试试下面的代码,看看它是否能让你更接近你的目标。

function fillText(ctx, x, y, txt, font) {
    ctx.font = font;
    ctx.fillText(txt, x, y)
    const tm = ctx.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>

在这段代码中,我用从measureText得到的值绘制了一些文本和一个矩形,正如您所看到的,这些值正确匹配

相关问题