如何在 html 画布中围绕文本绘制矩形?

Tom*_*Tom 2 html javascript canvas

我知道我读过一些关于画布中的上升和字体高度的内容,但我根本不明白。

首先,为什么文本是从右到上绘制的,而不是像矩形那样从右到下绘制的。我在文档中找不到任何地方。然后,如果我想在字母周围绘制一个矩形,尤其是低于基线的“y”或“p”,我该怎么办?

我有一个带有文字的画布

 ctx.beginPath();
  ctx.fillText('Hello yyyqqqppp', 50, 50);
  ctx.fillStyle = 'red';
  ctx.fill();
  ctx.closePath();
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能在它周围绘制矩形?

提前致谢!

mar*_*rkE 5

以下是在文本周围绘制矩形的一些关键点

如果您希望文本从左上角对齐,则可以设置以下上下文对齐属性:

context.textAlign='left';  // this is the default to align horizontally to the left
context.textBaseline='top';  // text will be aligned vertically to the top
Run Code Online (Sandbox Code Playgroud)

您可以使用以下上下文方法测量文本的水平宽度:

// set the font size and font face before measuring
context.font='14px verdana';
var textWidth=context.measureText('Hello').width;
Run Code Online (Sandbox Code Playgroud)

没有原生画布方法来测量文本高度,但对于我使用过的大多数字体和非极端字体大小,您可以获得高度的近似值,如下所示:

var lineHeight=fontsizeInPixels * 1.286;
Run Code Online (Sandbox Code Playgroud)

示例代码和演示:

context.textAlign='left';  // this is the default to align horizontally to the left
context.textBaseline='top';  // text will be aligned vertically to the top
Run Code Online (Sandbox Code Playgroud)
// set the font size and font face before measuring
context.font='14px verdana';
var textWidth=context.measureText('Hello').width;
Run Code Online (Sandbox Code Playgroud)
var lineHeight=fontsizeInPixels * 1.286;
Run Code Online (Sandbox Code Playgroud)