The CanvasRenderingContext2D
.textAlign
property of the Canvas 2D API specifies the current text alignment being used when drawing text. Beware that the alignment is based on the x value of the CanvasRenderingContext2D.fillText method. So if textAlign="center", then the text would be drawn at x-50%*width.
Syntax
ctx.textAlign = "left" || "right" || "center" || "start" || "end";
Options
Possible values:
- 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).
The default value is start
.
Examples
Using the textAlign
property
This is just a simple code snippet using the textAlign
property to set a different text alignment.
HTML
<canvas id="canvas"></canvas>
JavaScript
var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.font = '48px serif'; ctx.textAlign = 'left'; ctx.strokeText('Hello world', 0, 100);
Edit the code below and see your changes update live in the canvas:
Playable code
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="Edit" /> <input id="reset" type="button" value="Reset" /> </div> <textarea id="code" class="playable-code"> ctx.font = '48px serif'; ctx.textAlign = 'left'; ctx.strokeText('Hello world', 0, 100);</textarea>
var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var edit = document.getElementById('edit'); var code = textarea.value; function drawCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; drawCanvas(); }); edit.addEventListener('click', function() { textarea.focus(); }) textarea.addEventListener('input', drawCanvas); window.addEventListener('load', drawCanvas);
Specifications
Specification | Status | Comment |
---|---|---|
WHATWG HTML Living Standard The definition of 'CanvasRenderingContext2D.textAlign' in that specification. |
Living Standard |
Browser compatibility
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | 3.5 (1.9.1) | 9 | (Yes) | (Yes) |
Feature | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | 1.0 (1.9.1) | (Yes) | (Yes) | (Yes) |
See also
- The interface defining it,
CanvasRenderingContext2D
.