On an earlier page about drawing text and images the following function was shown. A line has been added to the onload function to decrement DATA.n
, to make the awaitLoaded()
work in the game outline in the previous section.
function loadImage(filePath)
{
let im = new Image();
im.loaded = false;
im.onerror = function()
{
alert('Failed to load ' + filePath);
};
im.onload = function()
{
im.loaded = true;
DATA.n--;
};
im.src = filePath;
return im;
}
That may be called as many times as there are images needing to be loaded. The loading will take place while the rest of the program continues. But we need to be sure each image has loaded before attempting to draw it on the canvas. That is why we have the property im.loaded
in the onload()
method. When the Image
is first constructed by the new
operator the property is false
.
When loading several images set a variable to how many are to be loaded before starting to load them. Then in im.onload()
add the line decrementing that count by one. Then we know when all have been loaded. That is the purpose of awaitLoading()
on the earlier page.
In the image below a single loaded image of a tree has been drawn in 4 places at different sizes to start to give an impression of perspective. Each placement was done with
DATA.g2.drawImage(tree, x, y, width, height);
with different values of the 4 parameters. Also notice that one of the trees goes off the edge of the image. As mentioned earlier, the browser takes care of such clipping automatically and we do not have to worry about it. The image is in PNG format with some transparency. I prepare such images from my own photos by using Affinity Photo.