It's important to load images before drawing them on the canvas, otherwise you may run into complication. I'm using this technic when I need to load a bunch of images. we can also add extra variable to them *( like the size of a game sprite for example ) *

You can find the final result without any frills here

let's start

First we need to create an array that will contain all the images we want to load

  let images_stock = [
  {
    name: "corgi",
    url: "https://image.ibb.co/k5CmjG/corgi.jpg",
    // custom variable can be added here
  },
  {
    name: "puppy",,
    url: "https://image.ibb.co/etHxrw/puppy.jpg",
    // custom variable can be added here
  },
  {
    name: "labrador",
    url: "https://image.ibb.co/dJZ5db/labrador.jpg",
    // custom variable can be added here
  }
];


And we also need to declare two important variables, they will be usefull to know when the loading is complete.

  let image_loaded = 0,
    image_to_load = images_stock.length;

This variable will contain every images at the end of the loading

  var images = {};
// and we'll pass through it to draw the images on the canvas like for example
// ctx.drawImage(images.puppy.img, 0, 0);
// or
// ctx.drawImage(images["puppy"].img, 0, 0);

The functions

The code is pretty straightforward right now we need to declare three frunctions.

the first function will assign every images in the "images" object.

  function processImage() {
  for (let i = 0; i < image_to_load; i++) {
    let subject = images_stock[i];
    subject.img = loadImage(subject.name, subject.url);
    images[subject.name] = subject;
  }
}

like so ...

  Object { corgi: {…}, puppy: {…}, labrador: {…} }

But will add a new propiety to the object.

    subject.img = loadImage(subject.name, subject.url);

this function will create an Image object with an onLoad event and will return it to the original.

  function loadImage(name, url) {
  let img = new Image();
  img.onload = () => {
    console.log(name + " loaded");
    load();
  };
  img.src = url;
  return img;
}

When the onload event is complete it will trigger the load() function, I hope the code is pretty self explanatory at this stage

  function load() {
  image_loaded += 1;
  if (image_loaded === image_to_load) {
    init();
  }
}

This function will compare the number of image we need to load with the number of images we have in total.

When all the images are loaded the init() function get triggered and you can finaly use your images in it :) !


1,778 0 7