我想绘制多个图像,但它仅适用于最后一个图像

时间:2017-11-11 17:08:15

标签: javascript

这个函数是目标对象中的make "cards"数组,我添加了一些代码来绘制"cards"数组中的每个元素(参见标记:这部分),但它不起作用。我该怎么办?

var player = {
  cards = [];
};

function giveNCards(cardsArr, target, n) {
  target.cards = [];
  for (var i = 0; i < n; i++) {
    target.cards.push(cardsArr.pop());
  }
  ///////////   this part   //////////
  for (var i = 0; i < target.cards.length; i++) {
    var cardImage = new Image();
    cardImage.onload = (function(value) {
      return function() {
        ctx.drawImage(this, i * 100, 0);
      }
    })(i);

    cardImage.src = "./images/" + target.cards[i] + ".png"
  }
  //////////////////////////////////////////
  console.log(target.cards);
  return target.cards;
}

2 个答案:

答案 0 :(得分:0)

请注意,您在IFFE中使用的i值来自全局范围,因此您始终修改相同的值

var player = {
  cards = [];
};

function giveNCards(cardsArr, target, n) {
  target.cards = [];
  for (var i = 0; i < n; i++) {
    target.cards.push(cardsArr.pop());
  }
  ///////////   this part   //////////
  for ( var i = 0; i < target.cards.length; i++ ){
     var cardImage = new Image();
     cardImage.onload = (function(value){
         return function(){
             ctx.drawImage(this, value * 100, 0);
             // -------------------^
         }
     })(i);

     cardImage.src = "./images/" + target.cards[i] + ".png"
  }
  //////////////////////////////////////////
  console.log(target.cards);
  return target.cards;
}

答案 1 :(得分:0)

cardImage在每个循环中被覆盖。

变量(当使用&#39; var&#39;关键字定义时)是函数(函数范围)的本地变量,并且可以提升&#39; (移到顶部)。那是什么意思?基本上,您的代码将运行如下:

function giveNCards(cardsArr, target, n) {
  var i, cardImage // <-- cardImage defined first here (hoisted) 

  target.cards = [];
  for (i = 0; i < n; i++) {
    target.cards.push(cardsArr.pop());
  }
  for (i = 0; i < target.cards.length; i++ ){
     cardImage = new Image();
     cardImage.onload = (function(value){
         return function(){
             ctx.drawImage(this, i * 100, 0);
         }
     })(i);

     cardImage.src = "./images/" + target.cards[i] + ".png"
  }
  console.log(target.cards);
  return target.cards;
}

对此最简单的解决方法(尽管还有其他方法)是将第二个for循环的内容移动到另一个函数,这将赋予它自己的范围。

function giveNCards(cardsArr, target, n) {
  var i

  target.cards = [];
  for (i = 0; i < n; i++) {
    target.cards.push(cardsArr.pop());
  }
  for (i = 0; i < target.cards.length; i++ ){
       renderCard(target, i)
  }
  console.log(target.cards);
  return target.cards;
}

function renderCard(target, i) {
     var cardImage = new Image();
     cardImage.onload = (function(value){
         return function(){
             ctx.drawImage(this, i * 100, 0);
         }
     })(i);

     cardImage.src = "./images/" + target.cards[i] + ".png"
}