1

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 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.