-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
66 lines (53 loc) · 1.41 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const SQUARE_SIZE = 20;
const MARGIN = 2;
const ACTIVE_COLOR = '#fab';
const COLOR = '#eee';
class FieldCanvas {
constructor(selector, matrix) {
this.container = document.querySelector(selector);
this.context = this.container.getContext('2d');
this.matrix = matrix;
this.draw();
}
draw() {
this.matrix.forEach((row, rowIndex) =>
this.drawRow(row, rowIndex)
);
}
redraw(matrix) {
this.matrix = matrix;
this.draw();
}
drawRow(row, rowIndex) {
row.forEach((square, squareIndex) =>
this.drawSquare(square, rowIndex, squareIndex)
);
}
drawSquare(square, rowIndex, squareIndex) {
const args = [
squareIndex * SQUARE_SIZE + MARGIN * squareIndex,
rowIndex * SQUARE_SIZE + MARGIN * rowIndex,
SQUARE_SIZE,
SQUARE_SIZE
];
const color = square ? ACTIVE_COLOR : COLOR;
this.context.fillStyle = color;
this.context.fillRect(...args);
}
}
function generateMatrix(size) {
const matrix = [];
for (let i = 0; i < size; i += 1) {
for (let j = 0; j < size; j += 1) {
if (!matrix[j]) {
matrix[j] = [];
}
matrix[j].push(Math.random() > .5 ? true : false);
}
}
return matrix;
}
new FieldCanvas(
'#canvas',
generateMatrix(20)
);