Свойство textAlign на канвасе

Определение и использование

textAlign Атрибут в зависимости от якоря устанавливает или возвращает текущий способ выравнивания текстового контента.

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

Hint: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 examples. Please study the effect 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 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

Поддержка браузерами

Числа в таблице указывают на первую версию браузера, которая полностью поддерживает этот атрибут.

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

Комментарий:Internet Explorer 8 и более ранние версии не поддерживают элемент <canvas>.