Categories
JavaScript Answers

How to run code when drawing is finished drawing on an HTML5 Canvas with JavaScript?

Spread the love

Sometimes, we want to run code when drawing is finished drawing on an HTML5 Canvas with JavaScript.

In this article, we’ll look at how to run code when drawing is finished drawing on an HTML5 Canvas with JavaScript.

How to run code when drawing is finished drawing on an HTML5 Canvas with JavaScript?

To run code when drawing is finished drawing on an HTML5 Canvas with JavaScript, we can call drawImage in the image’s onload method and run the code we want after drawImage is called.

For instance, we write:

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

to add a canvas element.

Then we write:

const img = new Image();
img.src = "https://i.picsum.photos/id/496/200/300.jpg?hmac=demLRv0UMwDhQHH6AEmbkJqlYuX27lnRH5N9FYcHBgw";
img.onload = () => {
  const canvas = document.querySelector('canvas');
  const context = canvas.getContext('2d');
  context.drawImage(img, 0, 0);
  console.log('finished drawing')
};

to draw the image in the canvas by selecting the canvas element.

Then we create an Image instance and set its onload property to a function that calls drawImage.

We select the canvas with document.querySelector and its context with getContext.

Then we call drawImage to draw the image.

Finally, we log 'finished drawing' after the image is drawn in the canvas.

Conclusion

To run code when drawing is finished drawing on an HTML5 Canvas with JavaScript, we can call drawImage in the image’s onload method and run the code we want after drawImage is called.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *