Skip to content Skip to sidebar Skip to footer

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 ar

Solution 1:

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.


Post a Comment for "Javascript Canvas Element - Array Of Images"