嘿,我以前来过这里。我的问题是,我的任务是使用 Rects、lineTo、moveTo 等创建房屋的 HTML 画布绘图。我已经将房子创建为一个单独的 JavaScript 文件,并将它变成一个对象,以便在我的主画布页面上调用。
然而,当我最初创建房子时,它都在 canvas.js 文件中,这使得创建一个循环来用这个房子填充画布变得容易。
我现在要做的是复制这个循环,以 5*3 的方式用房屋填充画布(这将填满我的整个画布)。到目前为止我所做的是这样的;
我怎样才能把这段代码变成一个循环来在 5*3 网格中绘制房屋?PS 名称 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;
}
}
};