12,690,575 members (34,334 online)
Rate this:
See more:
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.
Posted 6-Nov-12 13:51pm

Rate this:

## Solution 1

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]);
}
```

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]);} );`
v2

Top Experts
Last 24hrsThis month
 OriginalGriff 300 Ashwin. Shetty 150 KarstenK 140 ppolymorphe 140 Maciej Los 105
 OriginalGriff 2,683 Peter Leow 1,855 Mika Wendelius 1,743 Jochen Arndt 1,224 ppolymorphe 1,106