English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML reference manual

HTML tag大全

HTML canvas textAlign attribute

textAlign is Canvas 2The D API describes the property of text alignment when drawing text. Note that this alignment is based on CanvasRenderingContext2The x value of the D.fillText method. So if textAlign="center", the text will be drawn at x-50%*width.

HTML canvas Reference Manual

Online example

at position150 draws a red line. Position150 is the positioning point for all defined text in the following example. Study the effect of each textAlign property value:

Your browser does not support HTML5 canvas tag.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML canvas textAlign property usage-Basic tutorial(oldtoolbag.com)</title>
</head>
<body>
<canvas id="myCanvas" width="3" height="2" style="border:1px solid #d3d3d3>
Your browser does not support HTML5 canvas tag.
</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
//at position150 creates a red line
ctx.strokeStyle="red";
ctx.moveTo(150,20);
ctx.lineTo(150,170);
ctx.stroke();
ctx.font="15px Arial";    
// indicates 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);
</script>
</body>
</html>
Test to see ‹/›

Browser compatibility

IEFirefoxOperaChromeSafari

Internet Explorer 9Firefox, Opera, Chrome, and Safari support textAlign Property.

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

Definition and Usage

The textAlign property sets or returns the current alignment of the text content based on the positioning point.

Usually, the text starts at the specified position, but if textAlign = "right" is set and the text is placed at position150 means that the text should be at position150 ends.

Tip:Please use fillText() orstrokeText() The method actually draws and locates text on the canvas.

Default Value:start
JavaScript Syntax:context.textAlign="center|end|left|right|start";

Attribute Value

ValueDescription
startDefault. The text starts at the specified position.
endThe text ends at the specified position.
centerThe center of the text is placed at the specified position.
leftThe text starts at the specified position.
rightThe text ends at the specified position.
HTML canvas Reference Manual