CanvasRenderingContext2D: textAlign 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

Canvas 2D API 的 CanvasRenderingContext2D.textAlign 属性指定绘制文本时使用的当前文本对齐方式。

对齐方式相对于 fillText() 方法的 x 值。例如,如果 textAlign"center",则文本的左边缘将位于 x - (textWidth / 2)

可能的值

"left"

文本左对齐。

文本右对齐。

"center"

文本居中对齐。

"start"

文本在行的正常起始位置对齐(对于从左到右的语言环境为左对齐,对于从右到左的语言环境为右对齐)。

"end"

文本在行的正常结束位置对齐(对于从左到右的语言环境为右对齐,对于从右到左的语言环境为左对齐)。

默认值为 "start"

示例

常规文本对齐

此示例演示了 textAlign 属性的三个“物理”值:"left""center""right"

HTML

html
<canvas id="canvas"></canvas>

JavaScript

js
const canvas = document.getElementById("canvas");
canvas.width = 350;
const ctx = canvas.getContext("2d");
const x = canvas.width / 2;

ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
ctx.stroke();

ctx.font = "30px serif";

ctx.textAlign = "left";
ctx.fillText("left-aligned", x, 40);

ctx.textAlign = "center";
ctx.fillText("center-aligned", x, 85);

ctx.textAlign = "right";
ctx.fillText("right-aligned", x, 130);

结果

依赖于方向的文本对齐

此示例演示了 textAlign 属性的两个依赖于方向的值:"start""end"。请注意,direction 属性手动设置为 "ltr",尽管这对于英语文本也是默认值。

HTML

html
<canvas id="canvas"></canvas>

JavaScript

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.font = "30px serif";
ctx.direction = "ltr";

ctx.textAlign = "start";
ctx.fillText("Start-aligned", 0, 50);

ctx.textAlign = "end";
ctx.fillText("End-aligned", canvas.width, 120);

结果

规范

规范
HTML
# dom-context-2d-textalign-dev

浏览器兼容性

另见