Home  >  Article  >  Web Front-end  >  Why Does My Canvas Image Not Draw? The Importance of Asynchronous Image Loading.

Why Does My Canvas Image Not Draw? The Importance of Asynchronous Image Loading.

Susan Sarandon
Susan SarandonOriginal
2024-10-30 12:32:52466browse

Why Does My Canvas Image Not Draw? The Importance of Asynchronous Image Loading.

Waiting for Image Load Before Drawing

When attempting to add an image to a canvas, it's crucial to ensure that the image is loaded before attempting to draw it. The issue you encountered in your code is due to the asynchronous nature of image loading.

To resolve this issue, you need to add a callback function to the onload event of the image. This callback function will be executed when the image has finished loading, ensuring that the image data is available before you try to draw it.

The corrected code below will wait for the image to load before drawing it to the canvas:

<code class="js">var canvas = document.getElementById('viewport'),
    context = canvas.getContext('2d');

make_base();

function make_base() {
  base_image = new Image();
  base_image.src = 'img/base.png';
  base_image.onload = function() {
    context.drawImage(base_image, 100, 100);
  };
}</code>

The above is the detailed content of Why Does My Canvas Image Not Draw? The Importance of Asynchronous Image Loading.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn