img.onload不在for循环中工作

时间:2016-08-30 20:57:27

标签: javascript loops canvas html5-canvas

我想在我创建的每个画布上绘制一个图像。但是当我运行代码时,最后一个代码就被绘制了。

Those canvas are empty

我认为这个问题是由for循环引起的。因为img.onload需要一些时间来加载。这是我的代码:

this.difficulty = $('#difficult').val();

var nSquares = parseInt($('#difficult').val()) * parseInt($('#difficult').val());

var pieceSize = 500 / this.difficulty;
var index = 1;

var dy = 0;
for(var i = 1; i <= this.difficulty;i++){
    var dx = 0;
    for(var j = 1; j <= this.difficulty;j++){
        var square = $('<canvas></canvas>');
        square.attr('id',"p" + index);
        square.attr('width',pieceSize);
        square.attr('height',pieceSize);

        $('#puzzle').append(square);

        var context = $('#p'+index)[0].getContext('2d');

        var img = new Image();

        img.onload = function(){
            context.drawImage(this,0,0,pieceSize,pieceSize);
        }

        img.src = this.image;


        index++;
        dx += pieceSize;

        console.log(dx+' '+dy);
    }
    dy += pieceSize;
}

0 个答案:

没有答案