javascript - js canvas drawImage not working with loop variable -
i'am trying load image on criteria canvas image loaded when give constant parameters drawimage() (drawimage constant commented) function.i can add many copy of image canvas want long use constants parameters.what's wrong code?please help..
here's code:
js:
slotsize=50px; playarea=9; var grid=[]; function rendergrid(grid) { for(var i=0,y=0;i<playarea;i++,y+=slotsize) { for(var j=0,x=0;j<playarea;j++,x+=slotsize) { ctx.fillstyle=grid[i][j]; if(grid[i][j]=="white") { grass=new image(); grass.onload=function() { //console.log(x+","+y); ctx.drawimage(grass,x,y,slotsize-2,slotsize-2); //ctx.drawimage(grass,0,0,slotsize-2,slotsize-2); works! } grass.src="../assets/grass.jpg"; } else { ctx.fillrect(x,y,slotsize,slotsize); } ctx.strokerect(x,y,slotsize,slotsize); } } } window.onload=function loadlocal() { canvas=document.getelementbyid("canvas"); ctx = canvas.getcontext("2d"); for(var i=0;i<playarea;i++) { grid[i]=[]; } for(var i=0;i<playarea;i++) { for(var i=j;i<playarea;i++) { grid[i][j]="white"; } } rendergrid(); }
html:
<canvas id="canvas" width="450" height="450"> browser not support canvas element.
http://plnkr.co/edit/h6h3un45ss6mxtqhlluz?p=preview
so want learn more context , scopes variables first. want learn more listeners , how communicate in asynchronous environment.
questions , comments welcome!
var slotsize=50; var playarea=9; var grid=[]; var canvas, ctx; var grass=new image(); function rendergrid() { for(var i=0,y=0;i<playarea;i++,y+=slotsize) { for(var j=0,x=0;j<playarea;j++,x+=slotsize) { var value = grid[i][j]; ctx.fillstyle = value; if(grid[i][j]=="white") { console.log(x,y); ctx.drawimage(grass,x,y,slotsize-2,slotsize-2); } else { ctx.fillrect(x,y,slotsize,slotsize); } ctx.strokerect(x,y,slotsize,slotsize); } } } window.onload=function loadlocal() { canvas=document.getelementbyid("canvas"); ctx = canvas.getcontext("2d"); for(var i=0;i<playarea;i++) { grid[i]=[]; for(var j=i;j<playarea;j++) { grid[i][j]="white"; } } grass.onload = rendergrid; grass.src = "http://images.clipartpanda.com/grass-clipart-grass-md.png"; }
Comments
Post a Comment