使用数组创建矩形 [英] Creating Rectangles with an Array

查看:80
本文介绍了使用数组创建矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我第一次使用HTML5,想使用包含x,y,w,h的数组创建矩形.我有一大堆对象,并且有一个用于创建它们的for循环,但是在使用数组编写矩形而不手动输入值时遇到了麻烦.这是我所写内容的简化版本.

Hi
I am using HTML5 for the first time and would like to create a rectangle using an array which contains the x, y, w, h. I have a big array of objects and a working for loops to create them but I am having trouble using the array to write a rectangle without typing the values manually. Here is a shortened down and simplified version of what I have written.

var Box = new Array();
Box[0] = (10, 10, 10, 10);

c.fillStyle="black";
c.strokeRect(Room[0]);


如果有人能告诉我如何使用这种数组,我将不胜感激.

谢谢.


If anyone could tell me how I could use this array in this way I would be very grateful.

Thanks.

推荐答案

当然,您只需指定要使用的数组的每个元素即可.
因此,在您的示例中-您将数字10重复了4次.我将它们插入.strokeRect以获得一个矩形,该矩形的一个角为10,10,另一个角为20,20

Sure, you just specify each element of the array you''d like to use.
So, in your example - you have the number 10 repeated 4 times. I''ll just plug them into .strokeRect to get a rect that has one corner at 10,10 and the other corner at 20,20

// array to hold all of our rooms
var houseRooms = [];

// first room
var curRoom = [10,10, 10,10];
houseRooms.push(curRoom);

// second room
curRoom = [20,20, 20,20];
houseRooms.push(curRoom);

// current index, lastIndex+1
var i, numRooms = houseRooms.length;
for (i=0; i<numRooms; i++)
{
  curRoom = houseRooms[i];
  c.strokeRect(curRoom[0], curRoom[1], curRoom[2], curRoom[3]);
}



由于houseRooms是一个数组,因此它包含的每个元素都是数组,因此我们可以避免上述循环中的步骤,而改为执行以下操作.



Since houseRooms is an array, as are each of the elements it contains, we can avoid a step in the above loop and do the following instead.

var i, numRooms = houseRooms.length;
for (i=0; i<numRooms; i++)
{
  c.strokeRect(houseRooms[i][0], houseRooms[i][1], houseRooms[i][2], houseRooms[i][3]);
}



但这又把我引到了另一点-我们可以用更少的代码来做到这一点..



But that then brings me to another point - we can do this with less code again..

houseRooms.forEach( drawOutline );
function drawOutline(elem)
{
 c.strokeRect(elem[0], elem[1], elem[2], elem[3]);
}


甚至更节俭,我们甚至不必命名该函数,我们可以在适当位置声明它.


or even more frugally, we don''t even have to name the function, we can declare it in place.

houseRooms.forEach( function(e){c.strokeRect(e[0], e[1], e[2], e[3]);} );


这篇关于使用数组创建矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆