D
D
Daniel2020-05-23 16:37:27
JavaScript
Daniel, 2020-05-23 16:37:27

What is the CORRECT way to insert images into canvas?

const img = new Image();
img.src = 'path/img.png';


And then what is the best way to do it canvas.drawImage(img, x, y);?
By placing in window.onload?
By placing in img.onload?
Or without anything?

Consider the following task: first draw the background, then the character.
When implemented without onload, nothing is drawn, because fails to load.
When implemented with img.onloadeither the character is superimposed on top of the background (which is what I need), or the background is superimposed on top of the character ...
When implemented with stuffing everything in window.onloadand trying to animate, I get an error about excessive recursion ...

In all the YouTube video guides on making games with JS, no one uses "onload"... And everything works. Why? Because their files have time to load before rendering due to the code execution time until the rendering itself, and the file just has time to load (unlike in my case, where I want to immediately draw what I loaded on the next line)?

So many incomprehensibility ... Thanks for the answers!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twoone, 2020-05-23
@twoone

An image is represented by a file stored on the server and containing information about pixels in the form of a two-dimensional array of numbers. The easiest way to get this data in your program is to load it with an Image object and then pass it to the drawImage method to draw it on the canvas. If you do not wait until the data is fully loaded, then there will simply be nothing to draw. So your goal is to fully load all the images and draw them in the correct order. The easiest way to achieve this is with a Promise.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question