-
Notifications
You must be signed in to change notification settings - Fork 0
/
Squares.js
115 lines (85 loc) · 2.47 KB
/
Squares.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/*! Animated Squares
*
* @author Livingston Samuel
* @license MIT License
*
*/
;(function (win, doc, Math) {
var getRandomColor = function () {
return 'rgba('+ Math.floor(Math.random()*255) +','+ Math.floor(Math.random()*255) +','+ Math.floor(Math.random()*255) +','+ Math.random().toFixed(1) +')';
};
var renderSquare = function (ctx, cols, x, y) {
ctx.fillStyle = getRandomColor();
ctx.fillRect(0, 0, cols, cols);
};
var Squares = function (board, options) {
var defaultOptions = {
width: doc.body.offsetWidth,
height: doc.body.offsetHeight,
colWidth: 20,
grid: {
color: '#f7f7f7',
width: 1
},
shapeFn: renderSquare
};
this.board = board;
this.options = _.assign(defaultOptions, options || {});
this.setup();
if(this.options.grid)
this.renderGrid();
};
Squares.prototype = {
setup: function () {
var options = this.options;
this.ctx = this.board.getContext('2d');
this.updateDimensions();
},
updateDimensions: function () {
var options = this.options;
this.board.width = options.width;
this.board.height = options.height;
},
renderGrid: function () {
var options = this.options,
ctx = this.ctx,
width = options.width,
height = options.height,
cols = options.colWidth;
ctx.save();
ctx.translate(0,0);
ctx.beginPath();
var x, y;
for (x = .5; x <= width; x += cols) {
ctx.moveTo(x, 0);
ctx.lineTo(x, height);
}
for (y = .5; y <= height; y += cols) {
ctx.moveTo(0, y);
ctx.lineTo(width, y);
}
ctx.closePath();
ctx.strokeStyle = options.grid.color;
ctx.strokeWidth = options.grid.width;
ctx.stroke();
ctx.restore();
},
renderShape: function (x, y) {
var cols = this.options.colWidth;
x = x * cols;
y = y * cols;
this.ctx.save();
this.ctx.translate(x, y);
this.options.shapeFn(this.ctx, cols, x, y)
this.ctx.restore();
},
tick: function () {
var cols = this.options.colWidth,
randomX = Math.floor((Math.random()*this.options.width)/cols),
randomY = Math.floor((Math.random()*this.options.height)/cols);
this.renderShape(randomX, randomY);
requestAnimationFrame(this.tick.bind(this));
}
};
win.Squares = Squares;
}(window, document, Math));