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:
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);
};
}
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3