最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Canvas Element - Array Of Images - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Sep 1, 2009 at 3:31 Ben ShelockBen Shelock 21k26 gold badges97 silver badges126 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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/so/img/logo.png");   
  image_array.push("http://www.google./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.

发布评论

评论列表(0)

  1. 暂无评论