I'am trying to load an image on some criteria into a canvas but the image is loaded only when I give a constant as parameters for the drawImage() (drawImage with constant commented) function.I can add as many copy of the image to canvas as I want as long as I use constants as parameters.What's wrong with my code?Please help..
Here's the 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">
Your browser does not support the canvas element.