【问题标题】:Javascript Canvas Element - Array Of ImagesJavascript Canvas 元素 - 图像数组
【发布时间】:2009-09-01 03:31:50
【问题描述】:

我只是在学习 JS,试图在没有 jQuery 的情况下做一些事情,我想做一些类似于 this 的东西,但是我想使用一组图像而不是一个。

我的图像数组是这样形成的

var image_array = new Array()
image_array[0] = "image1.jpg" 
image_array[1] = "image2.jpg"

而canvas元素就是这样写的。 (几乎完全取自 Mozilla 网站)

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

它在该代码中使用图像“sample.png”,但我想更改它以显示数组中的图像。每次循环显示一个不同的。

如果我没有很好地解释这一点,请道歉。

【问题讨论】:

    标签: javascript arrays loops canvas


    【解决方案1】:

    只需遍历数组,并使用其宽度和高度属性定位图像:

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

    查看this 示例。

    【讨论】:

    • 这些图像可能会以错误的顺序出现 - 在浏览器中加载图像时会调用 onload 方法。小图像可能会在大图像之前调用 onload,即使它出现在数组的后面。
    猜你喜欢
    • 2013-06-06
    • 1970-01-01
    • 2010-10-29
    • 2012-01-23
    • 1970-01-01
    • 2016-09-18
    • 2011-12-28
    • 1970-01-01
    • 2016-03-18
    相关资源
    最近更新 更多