views:

411

answers:

2

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.

+1  A: 

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.

CMS
These images might appear in the wrong order - the onload method is called when an image is loaded in the browser. A small image might call onload before a large one, even though it occurs later in the array.
andrewmu
A: 

Thank you so much for this question and answer! It was exactly what I was looking for!

Jen