How to Add a Text on the HTML5 <canvas> Element
Solution with Javascript
To add a text to the HTML <canvas> element, you need to use the fillText() or strokeText() methods, or you can use the combination of the two. You can also give color to your text, define the font and size, and even add gradients.
In the example below, we give a unique id attribute to the <canvas> element, which allows us to access the element easily with Javascript. We also set the width and height of the element.
Example of adding a text on the <canvas> element with the fillText() method:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
#canvas {
background: #59b8de;
width: 250;
height: 150;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillStyle = "white";
context.font = "bold 18px Arial";
context.fillText("Text", (canvas.width / 2) - 17, (canvas.height / 2) + 8);
</script>
</body>
</html>
So, we accessed the <canvas> element by using the getElementById method, after which retrieved the 2D context. Then, we set text color with the fillStyle property, specified the font and added our text on the <canvas> by using the fillText method.
Now, let’s try an example with the strokeText() method.
Example of adding a text on the <canvas> element with the strokeText() method:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
#canvas {
background: #59b8de;
}
</style>
</head>
<body>
<canvas id="canvas" width="250" height="100"></canvas>
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.font = "30px Arial";
context.strokeText("Text", 50, 50);
</script>
</body>
</html>