Next page | Contents page |

More about images

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.

A simple landscape with sun and trees
The Javascript language keeps on being augmented with new ways of doing things. There are newer ways of loading images. I know some readers will wonder why I stick to the older ways. It's because I know they work well (some of my programs load 100 or more images this way) and I think the newer ways add unnecessary complications.
Next page | Contents page |