I would like to create a class with an array of object in the constructor. The idea is to create rects in a canvas with the values inside the objects.
I have this array:
JavaScript
x
5
1
const blueBoxs = [
2
{ x: 38, y: 31, w: 50, h: 50 },
3
{ x: 47, y: 31, w: 25, h: 19 },
4
]
5
I tried the following:
JavaScript
1
17
17
1
class Collision {
2
constructor (boxs) {
3
this.boxs=boxs;
4
};
5
6
createBox(boxs=[]){
7
for (let box of boxs) {
8
ctx.fillStyle = 'blue'
9
ctx.fillRect(box.x, box.y, box.w, box.h)
10
}
11
return
12
};
13
};
14
15
let createBluebox= new Collision(blueBoxs);
16
createBluebox.createBox();
17
Thanks for your help.
Advertisement
Answer
As already written, the addition of this
works. See example with this.boxs
JavaScript
1
34
34
1
const blueBoxs = [
2
{
3
x: 38,
4
y: 31,
5
w:50,
6
h:50,
7
},
8
{
9
x: 47,
10
y: 31,
11
w:25,
12
h:19,
13
} ]
14
15
class Collision {
16
constructor (boxs) {
17
this.boxs=boxs;
18
};
19
20
createBox(boxs=[]){
21
for (let box of this.boxs) {
22
ctx.fillStyle = 'blue'
23
ctx.fillRect(box.x, box.y, box.w, box.h)
24
}
25
return
26
};
27
28
};
29
30
let canvas = document.getElementById("myCanvas");
31
var ctx = canvas.getContext("2d");
32
33
let createBluebox= new Collision(blueBoxs);
34
createBluebox.createBox();
JavaScript
1
2
1
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
2
Your browser does not support the HTML5 canvas tag.</canvas>