CanvasRenderingContext2D.textAlign - Web APIs 编辑

The CanvasRenderingContext2D.textAlign property of the Canvas 2D API specifies the current text alignment used when drawing text.

The alignment is relative to the x value of the fillText() method. For example, if textAlign is "center", then the text's left edge will be at x - (textWidth / 2).

Syntax

ctx.textAlign = "left" || "right" || "center" || "start" || "end";

Options

Possible values:

"left"
The text is left-aligned.
"right"
The text is right-aligned.
"center"
The text is centered.
"start"
The text is aligned at the normal start of the line (left-aligned for left-to-right locales, right-aligned for right-to-left locales).
"end"
The text is aligned at the normal end of the line (right-aligned for left-to-right locales, left-aligned for right-to-left locales).

The default value is "start".

Examples

General text alignment

This example demonstrates the three "physical" values of the textAlign property: "left", "center", and "right".

HTML

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

JavaScript

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);

Result

Direction-dependent text alignment

This example demonstrates the two direction-dependent values of the textAlign property: "start" and "end". Note that the direction property is manually specified as "ltr", although this is also the default for English-language text.

HTML

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

JavaScript

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);

Result

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'CanvasRenderingContext2D.textAlign' in that specification.
Living Standard

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:80 次

字数:5651

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文