Home > Web Front-end > JS Tutorial > 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
Release: 2024-10-30 12:32:52
Original
546 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template