Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
92 lines (81 loc) · 2.89 KB
/
Copy pathapp.js
File metadata and controls
92 lines (81 loc) · 2.89 KB
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
const canvas = document.querySelector('canvas');
ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
class Particle{
constructor(x, y, directionX, directionY, size, color) {
this.x = x;
this.y = y;
this.directionX = directionX;
this.directionY = directionY;
this.size = size;
this.color = color;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
update() {
if (this.x > canvas.width || this.x < 0) {
this.directionX = -this.directionX;
} else if(this.y > canvas.height || this.y < 0 ){
this.directionY = -this.directionY;
}
this.x += this.directionX;
this.y += this.directionY;
this.draw();
}
}
const particle1 = new Particle(10, 10, 50, 55, 2, '#f1f1f1');
let particlesArray = [];
function init() {
const numberOfParticles = (canvas.height * canvas.width) / 9000;
for (let i = 0; i < numberOfParticles; i++){
const size = (Math.random() * 2) + 1;
const x = Math.random() * ((innerWidth - 10) - 10 + 1) + 10;
const y = Math.random() * ((innerHeight - 10) - 10 + 1) + 10;
const directionX = cleanDirection();
const directionY = cleanDirection();
particlesArray.push(new Particle(x, y, directionX, directionY, size, "#F1F1F1"));
}
console.log(particlesArray);
}
init();
function cleanDirection() {
const random = Math.trunc(Math.random() * 2);
if (random) {
//de 0.5 à 1.5 non inclu, non trunc [0.5, 1.5[
return ((Math.random() * 1) + 0.5);
} else {
//de -1.5 à -0.5 non inclu, non trunc ]-1.5, -0.5]
return ((Math.random() * -1) + 0.5);
}
}
function animate() {
ctx.clearRect(0, 0, innerWidth, innerHeight);
for (let i = 0; i < particlesArray.length; i++){
particlesArray[i].update();
}
connect();
requestAnimationFrame(animate);
}
animate();
function connect() {
for (let i = 0; i < particlesArray.length; i++){
for (let j = i+1; j < particlesArray.length; j++){
const squaredDistanceX = (particlesArray[i].x - particlesArray[j].x) * (particlesArray[i].x - particlesArray[j].x);
const squaredDistanceY = (particlesArray[i].y - particlesArray[j].y) * (particlesArray[i].y - particlesArray[j].y);
const hypothenuse = squaredDistanceX + squaredDistanceY;
if (hypothenuse < (135 * 135)) {
ctx.strokeStyle = `rgba(240,240,240, ${1 - hypothenuse / (135 * 135)})`;
ctx.lineWidth = 0.4;
ctx.beginPath();
ctx.moveTo(particlesArray[i].x, particlesArray[i].y);
ctx.lineTo(particlesArray[j].x, particlesArray[j].y);
ctx.stroke();
}
}
}
}