在for循环中将变量传递给onload函数

时间:2014-05-17 01:03:16

标签: javascript html canvas for-loop

我有以下简单的JavaScript加载一堆图像并将它们放在HTML画布上(canvasCTX是2D画布上下文):

for (var i=0 ;i<10; i++) {   
  var placementX = i*25;
  var imageObj = new Image();
  imageObj.src = 'assets/png/' + i + '.png';
  imageObj.onload = function() {
    canvasCtx.drawImage(imageObj,placementX,0);
  };
}

现在我发现的问题是所有图像都放在同一个地方 - 循环创建的最后一个变量。我认为这是因为for循环在加载图像时继续运行,因为onload是一个异步事件。

如何确保每张图片在placementX的转弯处获得正确的for loop

3 个答案:

答案 0 :(得分:1)

试试这段代码。

function draw(placementX , imagePath)
{

  var image = document.createElement("img");
  image.src=imagePath;        
  console.log(placementX , "before loading");//to ensure that x befor image loading is the same after loading

  image.onload=(function()
  { 
                canvas.drawImage(image , placementX  , 0);
                console.log(placementX , " after loading");//to ensure that x befor image loading is the same after loading

  });
}

var placementX =0;

for (var i=0 ;i<10; i++) 
{   
     placementX = i*25;
     draw('assets/png/' + i + '.png' , placementX );

}

答案 1 :(得分:0)

使用闭包。

for (var i=0 ;i < 10; i++) {   
    (function(x){
        var placementX = x*25;
        var imageObj = new Image();
        imageObj.src = 'assets/png/' + x + '.png';
        imageObj.onload = function() {
        canvasCtx.drawImage(imageObj,placementX,0);
        };
    })(i);

}

答案 2 :(得分:0)

    var i=0
    function update_image()
    { if(i<10)
    {   
          var placementX = i*25;
          var imageObj = new Image();
          imageObj.src = 'assets/png/' + i + '.png';
          imageObj.onload = function() {
            canvasCtx.drawImage(imageObj,placementX,0);
           i++;
    update_image();
          }
        }
update_image();