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)
.
ctx.textAlign = "left" || "right" || "center" || "start" || "end";
可能的值:
"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).
默认值为
"start"
.
This example demonstrates the three "physical" values of the
textAlign
特性:
"left"
,
"center"
,和
"right"
.
<canvas id="canvas"></canvas>
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);
This example demonstrates the two direction-dependent values of the
textAlign
特性:
"start"
and
"end"
。注意,
direction
property is manually specified as
"ltr"
, although this is also the default for English-language text.
<canvas id="canvas"></canvas>
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 实时标准
The definition of 'CanvasRenderingContext2D.textAlign' in that specification. |
实时标准 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
textAlign
|
Chrome Yes | Edge 12 | Firefox 3.5 | IE Yes | Opera Yes | Safari Yes | WebView Android Yes | Chrome Android Yes | Firefox Android 4 | Opera Android Yes | Safari iOS Yes | Samsung Internet Android Yes |
完整支持
CanvasRenderingContext2D
CanvasRenderingContext2D
addHitRegion()
arc()
arcTo()
beginPath()
bezierCurveTo()
clearHitRegions()
clearRect()
clip()
closePath()
createImageData()
createLinearGradient()
createPattern()
createRadialGradient()
drawFocusIfNeeded()
drawImage()
drawWidgetAsOnScreen()
drawWindow()
ellipse()
fill()
fillRect()
fillText()
getImageData()
getLineDash()
getTransform()
isPointInPath()
isPointInStroke()
lineTo()
measureText()
moveTo()
putImageData()
quadraticCurveTo()
rect()
removeHitRegion()
resetTransform()
restore()
rotate()
save()
scale()
scrollPathIntoView()
setLineDash()
setTransform()
stroke()
strokeRect()
strokeText()
transform()
translate()