绘制文本

在上一章学习了如何应用样式和颜色之后,我们现在将学习如何在画布上绘制文本。

绘制文本

Canvas 渲染上下文提供了两种渲染文本的方法:

fillText(text, x, y [, maxWidth])

在指定的 (x,y) 位置填充给定的文本。可选填入最大宽度进行绘制。

strokeText(text, x, y [, maxWidth])

在指定的 (x,y) 位置描绘给定的文本轮廓。可选填入最大宽度进行绘制。

一个 fillText 示例

文本使用当前的 fillStyle 进行填充。

js
function draw() {
  const ctx = document.getElementById("canvas").getContext("2d");
  ctx.font = "48px serif";
  ctx.fillText("Hello world", 10, 50);
}

一个 strokeText 示例

文本使用当前的 strokeStyle 进行填充。

js
function draw() {
  const ctx = document.getElementById("canvas").getContext("2d");
  ctx.font = "48px serif";
  ctx.strokeText("Hello world", 10, 50);
}

文本样式

在上面的示例中,我们已经使用了 font 属性来使文本比默认大小稍大一些。还有一些属性可以让你调整文本在画布上的显示方式。

font = value

绘制文本时使用的当前文本样式。此字符串使用与 CSS font 属性相同的语法。默认字体为 10px sans-serif。

textAlign = value

文本对齐设置。可能的值:startendleftrightcenter。默认值为 start

textBaseline = value

基线对齐设置。可能的值:tophangingmiddlealphabeticideographicbottom。默认值为 alphabetic

direction = value

方向性。可能的值:ltrrtlinherit。默认值为 inherit

如果你之前使用过 CSS,这些属性可能对你来说很熟悉。

下面的图表来自 HTML 规范,演示了 textBaseline 属性支持的各种基线。

The em-over baseline is roughly at the top of the glyphs in a font, the hanging baseline is where some glyphs like आ are anchored, the middle is half-way between the em-over and em-under baselines, the alphabetic baseline is where characters like Á, ÿ, f, and Ω are anchored, the ideographic-under baseline is where glyphs like 私 and 達 are anchored, and the em-under baseline is roughly at the bottom of the glyphs in a font. The top and bottom of the bounding box can be far from these baselines, due to glyphs extending far outside em-over and em-under baselines.

一个 textBaseline 示例

此示例演示了各种 textBaseline 属性值。有关更多信息和详细示例,请参阅 CanvasRenderingContext2D.textBaseline 页面。

js
function draw() {
  const ctx = document.getElementById("canvas").getContext("2d");
  ctx.font = "48px serif";

  ctx.textBaseline = "hanging";
  ctx.strokeText("hanging", 10, 50);

  ctx.textBaseline = "middle";
  ctx.strokeText("middle", 250, 50);

  ctx.beginPath();
  ctx.moveTo(10, 50);
  ctx.lineTo(300, 50);
  ctx.stroke();
}

高级文本测量

如果你需要获取有关文本的更多详细信息,以下方法允许你测量它。

measureText()

返回一个 TextMetrics 对象,其中包含指定文本在当前文本样式下绘制时的像素宽度。

以下代码片段展示了如何测量文本并获取其宽度。

js
function draw() {
  const ctx = document.getElementById("canvas").getContext("2d");
  const text = ctx.measureText("foo"); // TextMetrics object
  text.width; // 16;
}

可访问性考虑

<canvas> 元素只是一个位图,不提供关于任何已绘制对象的任何信息。在画布上书写的文本可能会给依赖屏幕放大功能的用户带来可读性问题。画布元素内的像素不会缩放,放大时可能会变得模糊。这是因为它们不是矢量图形,而是由像素组成的字母形状集合。放大时,像素会变得更大。

Canvas 内容不会像语义 HTML 那样暴露给辅助技术。总的来说,你应该避免在可访问的网站或应用程序中使用 Canvas。替代方案是使用 HTML 元素或 SVG 来代替 Canvas。