How to write text on top of image in HTML5 canvas with JavaScript?

Sometimes, we want to write text on top of image in HTML5 canvas with JavaScript.

In this article, we’ll look at how to write text on top of image in HTML5 canvas with JavaScript.

How to write text on top of image in HTML5 canvas with JavaScript?

To write text on top of image in HTML5 canvas with JavaScript, we can use the fillText and drawImage methods.

For instance, we write:

<canvas style='width: 200px; height: 300px'></canvas>

to add a canvas element.

Then we write:

const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");
const imageObj = new Image();
imageObj.onload = () => {
  context.drawImage(imageObj, 10, 10);
  context.font = "40pt Calibri";
  context.fillText("hello!", 20, 20);
};
imageObj.src = "https://i.picsum.photos/id/45/200/300.jpg?hmac=mW2p9asL-scUozua98sWn1c03g7CYv7w7IIHwnFp4cM";

We select the canvas with document.querySelector.

Then we get the context with getContext.

Next, we create a new Image instance and set its onload property to a function that calls drawImage to draw the image onto the canvas.

And then we set the font and call fillText to set the font style and size and draw the text over the image.

Finally, we set the src property of the image to load the image.

imageObj.onload runs after the src property is set.

Conclusion

To write text on top of image in HTML5 canvas with JavaScript, we can use the fillText and drawImage methods.