Text 如何在给定右下角x,y的html-5画布上绘制文本

Text 如何在给定右下角x,y的html-5画布上绘制文本,text,html5-canvas,Text,Html5 Canvas,有人知道如何在给定右下角x,y坐标的html-5画布上绘制文本吗?.fillText(“text”,x,y)在x,y处绘制文本的左上角,我需要它在x,y处绘制右下角。如果有人知道答案,那将非常有帮助。使用measureText()函数 const width = context.measureText("text").width; const height = context.measureText("text").height; context.fillText("text", x - wid

有人知道如何在给定右下角x,y坐标的html-5画布上绘制文本吗?.fillText(“text”,x,y)在x,y处绘制文本的左上角,我需要它在x,y处绘制右下角。如果有人知道答案,那将非常有帮助。

使用measureText()函数

const width = context.measureText("text").width;
const height = context.measureText("text").height;
context.fillText("text", x - width, y - height);

使用“测量文本宽度”获取宽度

var width = ctx.measureText("text");
而且(如果你需要的话)你可以通过使用你的字体大小来得到大概的高度

ctx.font = "25px serif";
var height = parseInt(ctx.font.substring(0, 2)); // gets the font size
因为它呈现左下角,你只需要减去它

ctx.fillText("text", x - width, y);

对不起,没有高度。请尝试context.measureText(“text”).fontBoundingBoxAscent。如果这样做也不起作用,它也会返回未定义的值。查找高度似乎相当繁琐。这是一个近似解<代码>常量像素大小=24;context.font=pixelSize+“px衬线”;常量宽度=context.measureText(“文本”).width;常量高度=像素大小*3/4;填充文本(“文本”,200-宽度,200+高度)我刚测试过,注意到ctx.fillText(“text”,x,y)在x,y上打印文本的左下角。你也可以选择是的,谢谢,文本呈现在左下角,我会更新我的答案