Sometimes, we want to write text on an HTML5 canvas element with JavaScript.
In this article, we’ll look at how to write text on an HTML5 canvas element with JavaScript.
How to write text on an HTML5 canvas element with JavaScript?
To write text on an HTML5 canvas element with JavaScript, we call the fillText
method.
For instance, we write
<canvas id="my-canvas" width="200" height="120"></canvas>
to add a canvas element.
Then we write
const canvas = document.getElementById("my-canvas");
const context = canvas.getContext("2d");
context.fillStyle = "blue";
context.font = "bold 16px Arial";
context.fillText("hello", canvas.width / 2 - 17, canvas.height / 2 + 8);
to select the canvas with getElementById
.
We get the canvas’ context with getContext
.
And then we set the text style by setting the fillStyle
property.
We set the font by setting the font
property.
Finally, we call fillText
to write the 'hello'
at the given x and y coordinates.
Conclusion
To write text on an HTML5 canvas element with JavaScript, we call the fillText
method.