简体   繁体   中英

Not showing images in a html5 canvas (javascript)

I'm trying to show chess pieces on a board. The thing is: IF I let the "alert(img.src)" (thus creating a lot of alert boxes...), pieces are gonna show at the right places, BUT if I remove the alert, it shows only one piece in the up-right corner of my canvas.

What do you think is happening? Thanks!

for (var i=1;i<9;i++){
    for (var j=1;j<9;j++){
        var img=new Image();
        img.onload=function(){
                ctx.drawImage(img,p+sqs*(i-1)+(sqs-32)/2,p+bds-sqs*j+(sqs-32)/2,32,32);
        };
        img.src="img/"+squares[i][j]+".png";
        //alert(img.src);
    }
}

Your problem is Javascript closures. If you don't know about this, look it up . If you add an alert(i+','+j+','+img.src) to your onload function and run your program you'll see that the onload function is using the final values of the loop variable - ie 9,9.

To pass the values you actually want to pass, you need to create a new scope, using a self-invoking anonymous function. So your code should look like this:

for (var i=1;i<9;i++){
    for (var j=1;j<9;j++){
        var img=new Image();
        (function(i,j,img){
            img.onload=function(){
                ctx.drawImage(img,sqs*(i-1),sqs*(j-1),32,32);
            };
            img.src="http://placekitten.com/"+(30+i)+"/"+(30+j);
        })(i,j,img) ;
    }
}

Click here for a live example .

By the way, the reason your code worked when you had the alert(img.src) statement was that you were stopping the loop at every iteration, which had the effect that your onload function (which doesn't execute until the image is loaded) was using the correct i and j . Without the alert statement, the loop set (i,j) to (9,9) by the time any of the images had loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM