HTML canvas textAlign attribute
Definition and Usage
textAlign
The property sets or returns the current alignment of the text content based on the anchor point.
By default, text starts from the specified position, 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 defined texts below. Please study the effects of each textAlign property value:
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);
Syntax
context.textAlign="center|end|left|right|start";
Attribute Value
Value | Description |
---|---|
start | Default. Text starts at the specified position. |
end | Text ends at the specified position. |
center | The center of the text is placed at the specified position. |
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.