Click here to Skip to main content
15,071,729 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
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.

JavaScript
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

1 solution

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

JavaScript
// 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.

JavaScript
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..

JavaScript
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.

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

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900