Click here to Skip to main content
11,429,382 members (66,145 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Javascript HTML5
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

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

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

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



Advertise | Privacy | Mobile
Web04 | 2.8.150428.2 | Last Updated 6 Nov 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100