JavaScript的canvas元素 - 阵列图像中 [英] Javascript Canvas Element - Array Of Images

查看:168
本文介绍了JavaScript的canvas元素 - 阵列图像中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚学JS,试图做的事情没有jQuery的,我想做出类似的这个不过,我想用图像阵列而不只是一个。

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"

和canvas元素是这样写的。 (pretty从Mozilla网站多采取完全)

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);
          }
        }
      }
    }

它使用在code中的形象sample.png,但我想改变它从数组中显示图像。显示它循环一个不同的各一次。

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,如果我没有解释这一点。

Apoligies if I've not explained this well.

推荐答案

只是迭代这个数组,并通过使用其宽度和高度属性的图像的位置是:

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);  
  }  
}

这个例子。

这篇关于JavaScript的canvas元素 - 阵列图像中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆