English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
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:
<!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 ‹/›
IEFirefoxOperaChromeSafari
Internet Explorer 9Firefox, Opera, Chrome, and Safari support textAlign Property.
Note:Internet Explorer 8 and earlier versions do not support the <canvas> element.
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"; |
Value | Description |
---|---|
start | Default. The text starts at the specified position. |
end | The text ends at the specified position. |
center | The center of the text is placed at the specified position. |
left | The text starts at the specified position. |
right | The text ends at the specified position. |