This page is Ready to Use

Notice: The WebPlatform project, supported by various stewards between 2012 and 2015, has been discontinued. This site is now available on github.

textAlign

Summary

Returns or sets the text alignment value. See return value description below.

Property of apis/canvas/CanvasRenderingContext2Dapis/canvas/CanvasRenderingContext2D

Syntax

var result = CanvasRenderingContext2D.textAlign;
CanvasRenderingContext2D.textAlign = value;

Return Value

Returns an object of type StringString

Must be one of the following:

  • “start” (default)
  • “end”
  • “left”
  • “right”
  • “center”

Examples

<canvas id="myCanvas" width="300" height="150" style="border:1px solid blue;"></canvas>
<p>. . .</p>
<script>
var can=document.getElementById("myCanvas");
var ctxt=can.getContext("2d");
//draw a vertical line down the middle of the canvas
ctxt.strokeStyle="green";
ctxt.moveTo(150,0);
ctxt.lineTo(150,150);
ctxt.stroke();
//set the font
ctxt.font="16px Arial";
//show effect of textAlign values
ctxt.textAlign="start";
ctxt.fillText("START",150,40);
ctxt.textAlign="end";
ctxt.fillText("END",150,60);
ctxt.textAlign="left";
ctxt.fillText("LEFT",150,80);
ctxt.textAlign="right";
ctxt.fillText("RIGHT",150,100);
ctxt.textAlign="center";
ctxt.fillText("CENTER",150,120);
</script>

Notes

The exact alignment depends on whether the direction of HTMLCanvasElement is left-to-right (ltr) or right-to-left (rtl). The textBaseline value also determines the anchor point of the text.

Related specifications

W3C HTML Canvas 2D Specification
W3C Candidate Recommendation

Attributions