js canvas drawImage不使用循环变量

时间:2016-02-06 14:40:14

标签: javascript html5 canvas drawimage

我正在尝试将某些条件上的图像加载到画布中但是只有当我为drawImage()(带有常量注释的drawImage)函数提供常量时才加载图像。我可以添加尽可能多的只要我使用常量作为参数,我就可以将图像副本复制到画布。我的代码出了什么问题?请帮助..

以下是代码:
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.   

1 个答案:

答案 0 :(得分:0)

http://plnkr.co/edit/h6H3UN45sS6mxtQHlLUz?p=preview

因此,基本上您希望首先了解有关变量的上下文和范围的更多信息。然后,您想要了解有关Even Listeners以及如何在异步环境中进行通信的更多信息。

欢迎提出问题和意见!

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";
}