-
Notifications
You must be signed in to change notification settings - Fork 1
/
field.js
121 lines (106 loc) · 2.57 KB
/
field.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
116
117
118
119
120
121
(function( Math, global ) {
var TAU = Math.PI * 2,
random = Math.random,
innerW = global.innerWidth,
innerH = global.innerHeight,
colors = [
'rgba(0,63,122,0.65)',
'rgba(31,113,111,0.65)',
'rgba(177,150,56,0.65)',
'rgba(229,227,102,0.65)'
],
well = {
x2: innerW / 2,
y2: innerH / 2,
mass: 100
};
function getTime() {
return (new Date()).getTime();
}
function chooseColor() {
return colors[ -~( random() * 4 ) - 1];
}
function Field( ctxid, obj ) {
if (!( this instanceof Field )) return new Field( ctxid, obj );
this.canvas = document.getElementById( ctxid );
this.ctx = this.canvas.getContext( '2d' );
this.canvas.width = innerW;
this.canvas.height = innerH;
this.objs = [];
for ( var i = 0; i < obj.count; i++ )
this.objs.push({
r: obj.r,
x: obj.x,
y: obj.y,
dx: obj.dx(),
dy: obj.dy(),
color: chooseColor()
});
}
Fieldfn = Field.prototype;
Fieldfn.dcheck = function() {
var i = 0,
tobjs = this.objs,
tmpobj, tmpr, xdx, ydy;
for ( ; i < tobjs.length; i++ ) {
tmpobj = tobjs[i];
tmpr = tmpobj.r;
xdx = tmpobj.x + tmpobj.dx;
ydy = tmpobj.y + tmpobj.dy;
/* collision detection */
if ( xdx + tmpr > innerW || xdx - tmpr < 0 ) tmpobj.dx *= -1;
if ( ydy + tmpr > innerH || ydy - tmpr < 0 ) tmpobj.dy *= -1;
}
return this;
};
Fieldfn.clear = function() {
this.ctx.clearRect( 0, 0, innerW, innerH );
return this;
};
Fieldfn.draw = function() {
var i = 0,
tctx = this.ctx,
len = this.objs.length,
tobjs = this.objs,
tobj;
tctx.globalCompositeOperation = 'lighter';
for ( ; i < len; i++ ) {
tobj = tobjs[i];
tctx.fillStyle = tobj.color;
tctx.beginPath();
tctx.arc( tobj.x, tobj.y, tobj.r, 0, TAU, true );
tctx.closePath();
tctx.fill();
}
return this;
};
Fieldfn.increment = function( time ) {
var i = 0,
tobjs = this.objs,
len = tobjs.length,
Cr, a, x0, y0, x0y0, tobj;
for ( ; i < len; i++ ) {
tobj = tobjs[i];
/* physics for moving particles */
tobj.x += tobj.dx;
tobj.y += tobj.dy;
// resize circle radius based on velocity
tobj.r = 1 + Math.sqrt( Math.abs( tobj.dx ) + Math.abs( tobj.dy ));
}
return this;
};
// make visible
global.Field = Field;
// Utility method for displaying time
global.fpsCount = {
init : function() {
var elem = document.createElement( 'p' );
elem.id = 'fpsCount';
document.body.appendChild( elem );
},
print : function( time ) {
var elem = document.getElementById( 'fpsCount' );
elem.innerHTML = ( 1000 / time ).toFixed( 1 ) + ' fps';
}
};
})( Math, this );