对象的数组循环

Array loop for an object

本文关键字:循环 数组 对象      更新时间:2023-09-26

嘿,我以前来过这里。我的问题是,我的任务是使用Rects,lineTo,moveTo等创建房屋的HTML画布绘图。我已经将房子创建了一个单独的JavaScript文件,并将其变成了一个在我的主画布页面上调用的对象。

然而,当我最初创建房子时,它都在画布.js文件中,这使得创建一个循环来用这个房子填充画布变得容易。

我现在要做的就是复制这个循环,以 5*3 的方式用房屋填充画布(这将填充我的整个画布)。到目前为止,我所做的是这样的;

如何将这些代码转换为循环,以 5*3 的网格绘制房屋?P.S 房子这个名字是另一个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,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 ;