然而,当我最初创建房子时,它都在canvas.js文件中,这使得创建一个循环来填充画布,这个房子很容易。
我现在要做的就是复制这个循环,以5 * 3的方式填充画面(这将填满我的整个画布)。到目前为止我所做的就是这个;
如何将这个Hunk代码转换为循环以在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 :(得分: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 ;