为什么要这样创建图像

时间:2014-04-09 16:05:37

标签: javascript arrays canvas

我正在尝试这样做,所以这个数组显示属于数组的外星人但由于某些原因,当我将该函数作为游戏循环的一部分调用时,没有任何东西出现,我很难过:/

//设置外星人照片的数组。 var AliArray = new Array();

var Init = function (){

    var totalRows = 12; //How many rows of aliens to spawn  
    var totalCols = 12; //How many cols of aliens to spawn  
    // For loops that creates the multidemensional array [col][row]
    for (q = 0; q < 12; q++) {
        AliArray[q] = new Array();
    }
    var imgWidth = 50; // Defines image's width 
    var imgHeight = 18; // defines image's height
    var rng = Math.floor((Math.random() * 10) + 1); // Gives a random number so that it spawns different aliens once level is complete.
    for (var row = 0; row < totalRows; row++) {
        for (var col = 0; col < totalCols; col++) {
            AliArray[row][col] = new Image();
            var x = col * imgWidth;
            var y = row * imgHeight;
            AliArray[row][col].onload = drawAliens(AliArray, row, col, x, y);
            if (rng < 5) {
                AliArray[row][col].src = "images/alien1.png";
            }
            else if (rng > 5) {
                AliArray[row][col].src = "images/alien2x.png";
            }
            else {
                AliArray[row][col].src = "images/alien3.png";
            }
        }
    }
};

var drawAliens = function (AliArray, row, col, x, y) {
    return function () {
        ctx.drawImage(AliArray[row][col], x, y);
    }
};

任何反馈都会非常精彩,因为我无法解释为什么它当前没有加载图像。我设法做的最多就是加载图像,但即使按照正确的顺序,它们也会立即消失或者在画布后面。

1 个答案:

答案 0 :(得分:1)

尝试在新的html页面中通过此代码,然后更改图像的路径引用,似乎工作

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <meta charset="utf-8" />
  <title></title>
 </head>
 <body>
  <canvas id="c" width="300" height="300"></canvas>
  <script>

   var c = document.getElementById('c');
   var ctx = c.getContext('2d');
   var AliArray = [];
   var Init = function () {

   var totalRows = 12; //How many rows of aliens to spawn  
   var totalCols = 12; //How many cols of aliens to spawn  
   // For loops that creates the multidemensional array [col][row]
   for (q = 0; q < 12; q++) {
    AliArray[q] = new Array();
   }
   var imgWidth = 50; // Defines image's width 
   var imgHeight = 18; // defines image's height
   var rng = Math.floor((Math.random() * 10) + 1); // Gives a random number so that it spawns different aliens once level is complete.
   for (var row = 0; row < totalRows; row++) {
   for (var col = 0; col < totalCols; col++) {
     AliArray[row][col] = new Image();
     var x = col * imgWidth;
     var y = row * imgHeight;
       AliArray[row][col].onload = drawAliens(AliArray, row, col, x, y);
       AliArray[row][col].src = "baby gator logo.jpg";
   }
  }
 };

 var drawAliens = function (AliArray, row, col, x, y) {
 return function () {
   ctx.drawImage(AliArray[row][col], x, y);
 }
};

Init();
</script>
</body>
</html>