2013-11-02 114 views
0

嘿,再次,我以前来过这里。我的问题是,我的任务是使用Rects,lineTo,moveTo等创建一个House的HTML画布。我创建了一个单独的JavaScript文件,并将其转换为一个要在我的主画布页面上调用的对象。对象的数组循环

但是,当我最初创建房子时,它全部都在canvas.js文件中,这使得创建一个循环来填充这个房子的画布很容易。

我现在要做的就是复制这个循环以5 * 3的方式填充画布(这将填充我的整个画布)。我迄今为止所做的是这样的;

我怎样才能把这个代码块成一个循环来绘制一个5 * 3网格的房屋? P.S名称House是另一个JavaScript文件中的房屋绘图对象。

 houses = new Array(); 
     //Columns 
     houses.push(new House(0,100,"#ff0000")); 
     houses.push(new House(0,310,"#ff0000")); 
     houses.push(new House(0,520,"#ff0000")); 
     //row1 
     houses.push(new House(160,100,"#ff0000")); 
     houses.push(new House(320,100,"#ff0000")); 
     houses.push(new House(480,100,"#ff0000")); 
     houses.push(new House(640,100,"#ff0000")); 
     //row2 
     houses.push(new House(160,310,"#ff0000")); 
     houses.push(new House(320,310,"#ff0000")); 
     houses.push(new House(480,310,"#ff0000")); 
     houses.push(new House(640,310,"#ff0000")); 
     //row3 
     houses.push(new House(160,520,"#ff0000")); 
     houses.push(new House(320,520,"#ff0000")); 
     houses.push(new House(480,520,"#ff0000")); 
     houses.push(new House(640,520,"#ff0000")); 
    } 

    //this function will draw on the canvas for me!  
    function draw(){ 
     context.fillStyle = 'grey'; 
     context.fillRect(0, 0, canvas.width, canvas.height); 

     for(var i =0; i < houses.length; i+=1){ 
      houses[i].draw(context); 
     } 
    } 

    initialise(); 
    draw(); 
} 

我原来的代码循环之前,我不得不把房子绘图功能作为一个对象;

var drawGreen = false; 
for(var i=0; i < 5; i++){ 
    var pX=0+160*i; 

     for(var b=0; b < 5; b++){ 
     var pY=100+210*b; 
      drawHouse(pX,pY,drawGreen); 
      drawGreen = !drawGreen; 
     } 
    } 
}; 
+0

我的答案是否奏效? – GameAlchemist

+0

我可以看到它是如何工作的,但我认为我不明白的是整个创建房子作为另一个文件中的对象,并调用它而不是在同一个文件中构建房子。 –

+0

如果你能帮忙解释这一部分,因为这是我的讲座中没有解释的部分。 –

回答

1

您可以使用画布的平移和缩放来让您的画布充满您将要复制的房屋。我们假设你的绘制都从(0,0)开始,有x> 0,y> 0,并且可以计算drawWidth和drawHeight。
那么你可以使用像这样的位置绘制在画布上(XSHIFT,YSHIFT),大小为(tgtWidth,tgtHeight):

function retargetDraw (ctx, drawFunc, drawWidth, drawHeight, 
           xShift, yShift, tgtWidth, tgtHeight) { 

     var needScaling = ((drawWidth != tgtWidth) || (drawHeight != tgtHeight)); 
     ctx.save(); 
     ctx.translate(xShift, yShift); 
     if (needScaling) { 
      ctx.scale(tgtWidth/drawWidth, tgtHeight/drawHeight);     
     } 
     drawFunc(); 
     ctx.restore(); 
    } 

的Rq:如果图像绝不会进行缩放,你可以删除tgtWidth/tgtHeight,或者你可以使它们可选:

tgtWidth = tgtWidth || drawWidth ; 
tgtHeight = tgtHeight || drawHeight ;