-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCanvas Particles.html
135 lines (105 loc) · 2.59 KB
/
Canvas Particles.html
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
<!DOCTYPE html>
<html>
<head>
<title>Canvas Particles</title>
<style type="text/css">
body, html {
height:100%;
}
html {
font-size:62.5%;
}
body {
font-size = 1.6rem;
background-color:#000;
}
.flex-row {
display:flex;
}
.flex-col {
display:flex;
flex-direction :column;
}
.page-container {
width:100%;
height:100%;
box-sizing:border-box;
}
</style>
</head>
<body >
<div class="page-container">
<div class="page-container__inner">
<canvas id = "canvas"></canvas>
</div>
</div>
<script>
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const particles = [];
const num_particles = 1000;
var stop = false;
function getRandomColor() {
let r = 0;
let g = 0;
let b = 0;
r = Math.floor(Math.random() * 156 + 100);
g = Math.floor(Math.random() * 156 + 100);
b = Math.floor(Math.random() * 156 + 100);
const randomColor = `rgb(${r}, ${g}, ${b})`;
return randomColor;
}
const particle = function() {
this.x = canvas.width * Math.random();
this.y = canvas.height * Math.random();
this.vx = 4 * Math.random() - 2;
this.vy = 4 * Math.random() - 2; ;
this.color = getRandomColor();
//alert(this.color);
}
particle.prototype.draw = function(ctx) {
ctx.beginPath()
ctx.fillStyle = this.color;
//ctx.fillRect(this.x,this.y, 3,3);
ctx.arc(this.x,this.y, 1.5, 0, Math.PI * 2, false);
ctx.fill();
}
particle.prototype.update = function() {
this.x += this.vx;
this.y += this.vy;
if (this.x < 0 || this.x > canvas.width) {
this.vx = -this.vx;
}
if (this.y < 0 || this.y > canvas.height) {
this.vy = -this.vy;
}
}
function loop() {
if (stop) return ;
context.clearRect(0,0, canvas.width,canvas.height);
for (let i = 0; i < num_particles; i++) {
particles[i].update();
particles[i].draw(context);
}
requestAnimationFrame(loop);
}
function initCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
for (let i = 0; i < num_particles; i++) {
particles.push(new particle());
//alert(i);
}
loop();
}
initCanvas();
canvas.addEventListener('click', function(e){
stop = !stop;
if (!stop) {
requestAnimationFrame(loop);
}
});
//
</script>
</body>
</html>