Canvas textAlign Attribute

Definition and Usage

textAlign The attribute sets or returns the current alignment style of the text content based on the anchor point.

By default, text starts from the specified location, but if you set textAlign="right" and place the text at position 150, it will end at position 150.

Tip:using fillText() or strokeText() Methods actually draw and position text on the canvas.

Example

Create a red line at position 150. Position 150 is the anchor point for all the text defined in the following example. Please study the effects of each textAlign attribute value:

Your browser does not support the canvas tag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
// Create a blue line at position 150
ctx.strokeStyle="blue";
ctx.moveTo(150,20);
ctx.lineTo(150,170);
ctx.stroke();
ctx.font="15px Arial";
// Display 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 yourself

Syntax

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

Attribute value

Value Description
start Default. Text starts at the specified location.
end Text ends at the specified location.
center The center of the text is positioned at the specified location.
left Text is aligned to the left.
right Text is aligned to the right.

Technical details

Default value: start

Browser Support

The numbers in the table indicate the first browser version that fully supports this property.

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
4.0 9.0 3.6 4.0 10.1

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