Latest web development tutorials

HTML canvas textAlign property

HTML canvas Reference Manual HTML canvas Reference Manual

Examples

Create a red line at position 150. Position 150 is defined in the following examples all the anchor text. Please study the effect of each textAlign property values:

YourbrowserdoesnotsupporttheHTML5canvastag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

// Create a red line in position 150
ctx.strokeStyle="red";
ctx.moveTo(150,20);
ctx.lineTo(150,170);
ctx.stroke();

ctx.font="15px Arial";

// Show the different textAlign values
ctx.textAlign="start";
ctx.fillText("textAlign=start",150,60);
ctx.textAlign="end";
ctx.fillText("textAlign=end",150,80);
ctx.textAlign="left";
ctx.fillText("textAlign=left",150,100);
ctx.textAlign="center";
ctx.fillText("textAlign=center",150,120);
ctx.textAlign="right";
ctx.fillText("textAlign=right",150,140);

try it"

Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

Internet Explorer 9, Firefox, Opera, Chrome and Safari support textAlign property.

Note: 8 and earlier versions of Internet Explorer do not support the <canvas> element.


Definition and Usage

textAlign attributes as anchor sets or returns the text content of the current alignment.

Typically, the textstarting at the specified location, but if you set the textAlign = "right" and the text is placed to the position 150, the position 150 in the end.

Tip: Use fillText () or strokeText () method to actually draw and position the text on the canvas.

Defaults: start
JavaScript syntax: context .textAlign = "center | end |left | right | start";

Property Value

描述
start 默认。文本在指定的位置开始。
end 文本在指定的位置结束。
center 文本的中心被放置在指定的位置。
left 文本在指定的位置开始。
right 文本在指定的位置结束。


HTML canvas Reference Manual HTML canvas Reference Manual