-
Notifications
You must be signed in to change notification settings - Fork 3
/
firefly-v0.1.js
106 lines (88 loc) · 2.79 KB
/
firefly-v0.1.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
function firefly(id, num, sz, color) {
if (document.getElementById("fireflyLayer") != null) {
var canvas = document.getElementById("fireflyLayer");
} else {
var canvas = document.createElement('canvas');
div = document.getElementById(id);
div.style.position = "relative";
canvas.id = "fireflyLayer";
canvas.height = div.offsetHeight;
canvas.width = div.offsetWidth;
canvas.style.position = "absolute";
canvas.style.zIndex = 100;
canvas.style.left = "0";
canvas.style.top = "0";
div.appendChild(canvas);
}
var h = canvas.height;
var w = canvas.width;
sketch(num, sz, color, h, w);
}
function sketch(num, sz, color, h, w) {
var mainCanvas = document.getElementById("fireflyLayer");
var mainContext = mainCanvas.getContext('2d');
mainContext.clearRect(0, 0, w, h);
var circles = new Array();
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
function Circle(radius, speed, width, xPos, yPos) {
this.radius = radius;
this.speed = speed;
this.width = width;
this.xPos = xPos;
this.yPos = yPos;
this.opacity = .05 + Math.random() * .8;
this.counter = 0;
var signHelper = Math.floor(Math.random() * 2);
if (signHelper == 1) {
this.sign = -1;
} else {
this.sign = 1;
}
}
Circle.prototype.update = function() {
this.counter += this.sign * this.speed;
mainContext.beginPath();
mainContext.arc(this.xPos + Math.cos(this.counter / w) * this.radius,
this.yPos + Math.sin(this.counter / h) * this.radius,
this.width,
0,
Math.PI * 2,
false);
mainContext.closePath();
var hex = color.replace('#','');
var r = parseInt(hex.substring(0,2), 16);
var g = parseInt(hex.substring(2,4), 16);
var b = parseInt(hex.substring(4,6), 16);
mainContext.fillStyle = 'rgba(' + r + ', ' + g + ', ' + b + ', ' + this.opacity + ')';
mainContext.fill();
};
var szNum;
if (sz == "big") { szNum = 10; }
else if (sz == "medium") { szNum = 5; }
else if (sz == "small") { szNum = 3; }
else if (sz == "tiny") { szNum = 1; }
else { szNum = 5; }
function drawCircles() {
for (var i = 0; i < num; i++) {
var randomX = Math.round(Math.random() * w);
var randomY = Math.round(Math.random() * h);
var speed = .2 + Math.random() * 3;
var size = Math.random() * szNum;
var circle = new Circle(100, speed, size, randomX, randomY);
circles[i] = circle;
}
draw();
}
drawCircles();
function draw() {
mainContext.clearRect(0, 0, w, h);
for (var i = 0; i < circles.length; i++) {
var myCircle = circles[i];
myCircle.update();
}
requestAnimationFrame(draw);
}
};