Canvas Text
HTML5 canvas allows creating text using font and text properties. See examples of the fillText, strokeText properties, and example of adding color and centering text.
HTML5 canvas allows creating text using different font and text properties presented below:
Properties and Methods
| Property / Method | Description |
|---|---|
| font | It returns the current font settings and can be set to change the font. |
| textAlign | It returns the current text alignment settings and can be set to change the alignment. The property has the following values: start, end, left, right, and center. Note that start and end depend on the text direction. |
| textBaseline | It returns the current baseline alignment settings and can be set to change the baseline alignment. The property has the following values: top, hanging, middle, alphabetic, ideographic, and bottom. |
| fillStyle | Sets the color used to fill text. |
| strokeStyle | Sets the color used to stroke text. |
| fillText(text, x, y) | It draws a filled text at the position indicated by the given coordinates x and y. |
| strokeText(text, x, y) | It strokes the text at the position indicated by the given coordinates x and y. |
Example of the fillText() method:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<canvas id="exampleCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("exampleCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World", 70, 80);
</script>
</body>
</html>Example of the strokeText() method:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<canvas id="exampleCanvas" width="250" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("exampleCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "27px Arial";
ctx.strokeText("Canvas text", 40, 70);
</script>
</body>
</html>Example of adding color and centering text:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<canvas id="exampleCanvas" width="400" height="250" style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("exampleCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "40px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("Canvas Text", canvas.width / 2, canvas.height / 2);
</script>
</body>
</html>Practice
Practice
What is the functionality of the HTML5 canvas 'fillText()' method in relation to text?