HTML Canvas Text Alignment
HTML Canvas Text Alignment
To align text in the canvas, we use two properties:
-
textBaseline
- defines the baseline (the vertical alignment) of text -
textAlign
- defines the horizontal alignment of text
The textBaseline Property
The textBaseline
property defines the baseline (the vertical alignment) of text.
The textBaseline
property can have the following values:
- "top"
- "hanging"
- "middle"
- "alphabetic" - this is default
- "ideographic"
- "bottom"
Example
Demonstration of the different values for the textBaseline
property:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// Create a line
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(0,75);
ctx.lineTo(500,75);
ctx.stroke();
ctx.closePath();
ctx.font = "20px Arial";
ctx.fillStyle = "purple";
ctx.textBaseline
= "top";
ctx.fillText("top", 5, 75);
ctx.textBaseline = "hanging";
ctx.fillText("hanging", 40, 75);
ctx.textBaseline = "middle";
ctx.fillText("middle", 120, 75);
ctx.textBaseline = "alphabetic";
ctx.fillText("alphabetic", 190, 75);
ctx.textBaseline = "ideographic";
ctx.fillText("ideographic", 295, 75);
ctx.textBaseline = "bottom";
ctx.fillText("bottom", 410, 75);
</script>
Try it Yourself »
The textAlign Property
The textAlign
property defines the
horizontal alignment of text.
The textAlign
property can have the following values:
- "left"
- "right"
- "center"
- "start" - this is default
- "end"
Example
Demonstration of the different values for the textAlign
property:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// Create a line
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(250,0);
ctx.lineTo(250,250);
ctx.stroke();
ctx.closePath();
ctx.font = "20px Arial";
ctx.fillStyle = "purple";
ctx.textAlign
= "center";
ctx.fillText("center", 250, 20);
ctx.textAlign =
"start";
ctx.fillText("start", 250, 50);
ctx.textAlign = "end";
ctx.fillText("end", 250, 80);
ctx.textAlign = "left";
ctx.fillText("left",
250, 110);
ctx.textAlign = "right";
ctx.fillText("right", 250, 135);
</script>
Try it Yourself »
Center Text
Example
Center text both vertically and horizontally in the canvas:
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.font = "30px Verdana";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("Hello World", canvas.width/2, canvas.height/2);
</script>
Try it Yourself »