1

I am not used to the syntax yet. How would I make the rect in to a double array? In the programming language I used, you could put shapes into a double array, like so:

box[i][j] = Shapes.AddRectangle(GraphicsWindow.Width/10, GraphicsWindow.Height/10)

Here's my HTML/JavaScript code:

var cnv = document.getElementById("canvas");
var ctx = cnv.getContext('2d');
var width = cnv.width;
var height = cnv.height;
var size = 10;
var box[][] = new rect[width / size][height / size];

function drawGrid() {

  var i = null;
  var j = null;
  for (i = 1; i <= width / size; i++) {
    for (j = 1; j <= height / size; j++) {
      box[i][j] = ctx.rect((i - 1) * size, (j - 1) * size, size, size);
      ctx.fillStyle = 'red';
      ctx.fill();
    }
  }
  return;
}
drawGrid();
<html>

  <head>

    <body>
      <canvas id="canvas" width="250" height="250" style="border: 1px solid black;">
      </canvas>
    </body>

    <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  </head>

</html>
Omar Einea
  • 2,478
  • 7
  • 23
  • 35
Robot2425
  • 29
  • 6

2 Answers2

1

I think the issue you're having is looking for "double array" - rather than multi dimensional array

or more specifically two dimensional array

here is an existing page that covers that topic: How can I create a two dimensional array in JavaScript?

So in your case that looks like this:

var box = [];
box.length = width / size;
for (var i = 0; i < box.length;++i){
  box[i] = [];
  box[i].length = height / size;
}

But, it will just be a two dimensional array filled with null values.

Tim
  • 539
  • 2
  • 9
0

In Javascript, multidimensional arrays are not created using the T [][] var syntax. Instead the most common ways might be to either make them on initialisation as such as:

var obj = [ 
    [
        { x: 60, y: 10 }, // obj [0] [0]
        { x: -5, y: 40 }  // obj [0] [1]
    ], 
    [ 
        { x: 10, y: 20 }  // obj [1] [0]
    ] 
];

console.log (obj [0] [0].x); // 60
console.log (obj [1] [0].y); // 20

Or you can populate it dynamically in a loop as you have tried to do above.

I did some housekeeping on your code but here is a fiddle which makes your grid and then places all of the coordinate data into an object. But notice the object starts empty and the data is added to the object in the loop.

You can open the console to see what the coordinate matrix looks like.

Anders
  • 84
  • 1
  • 3