Ben Shelock
Ben Shelock

Reputation: 20993

Javascript Canvas Element - Array Of Images

I'm just learning JS, trying to do things without jQuery, and I want to make something similar to this however I want to use an array of images instead of just the one.

My image array is formed like this

var image_array = new Array()
image_array[0] = "image1.jpg" 
image_array[1] = "image2.jpg"

And the canvas element is written like this. (Pretty much entirely taken from the Mozilla site)

function draw() {
      var ctx = document.getElementById('canvas').getContext('2d');
      var img = new Image();
      img.src = 'sample.png';
      img.onload = function(){
        for (i=0;i<5;i++){
          for (j=0;j<9;j++){
            ctx.drawImage(img,j*126,i*126,126,126);
          }
        }
      }
    }

It uses the image "sample.png" in that code but I want to change it to display an image from the array. Displaying a different one each time it loops.

Apoligies if I've not explained this well.

Upvotes: 1

Views: 9457

Answers (1)

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 828050

Just iterate over the array, and position the images by using its width and height properties:

function draw() {  
  var ctx = document.getElementById('canvas').getContext('2d'),  
      img, i, image_array = [];  

  image_array.push("http://sstatic.net/so/img/logo.png");   
  image_array.push("http://www.google.com/intl/en_ALL/images/logo.gif");  
  // ...  

  for (i = 0; i < image_array.length; i++) {  
    img = new Image();  
    img.src = image_array[i];  
    img.onload = (function(img, i){ // temporary closure to store loop 
      return function () {          // variables reference 
        ctx.drawImage(img,i*img.width,i*img.height);  
      }  
    })(img, i);  
  }  
}  

Check this example.

Upvotes: 4

Related Questions