-
Notifications
You must be signed in to change notification settings - Fork 0
/
3-connecting-particles.js
97 lines (88 loc) · 2.99 KB
/
3-connecting-particles.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
// setup
const canvas = document.getElementById('canvas1')
const ctx = canvas.getContext('2d')
canvas.width = window.innerWidth
canvas.height = window.innerHeight
//ctx.strokeStyle = 'white'
//ctx.lineWidth = 5
console.log(ctx)
const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height)
gradient.addColorStop(0, 'white')
gradient.addColorStop(0.5, 'magenta')
gradient.addColorStop(1, 'blue')
ctx.fillStyle = gradient
ctx.strokeStyle = 'white'
class Particle {
constructor(effect){
this.effect = effect
this.radius = Math.random() * 5 + 2
this.x = this.radius + Math.random() * (this.effect.width - this.radius * 2)
this.y = this.radius + Math.random() * (this.effect.height - this.radius * 2 )
this.vx= Math.random() * 1 - 0.5
this.vy = Math.random() * 1 - 0.5
}
draw(context){
//context.fillStyle = 'hsl(' + this.x * 0.5 + ', 100%, 50%)'
context.beginPath()
context.arc(this.x, this.y, this.radius, 0, Math.PI * 2)
context.fill()
context.stroke()
}
update(){
this.x += this.vx
if (this.x > this.effect.width - this.radius || this.x < this.radius) this.vx *= -1
this.y += this.vy
if (this.y > this.effect.height - this.radius || this.y < this.radius) this.vy *= -1
}
}
class Effect {
constructor(canvas){
this.canvas = canvas
this.width = this.canvas.width
this.height = this.canvas.height
this.particles = []
this.numberOfParticles = 400
this.createParticles()
}
createParticles() {
for (let i = 0; i< this.numberOfParticles; i++){
this.particles.push(new Particle(this))
}
}
handleParticles(context){
this.connectParticles(context)
this.particles.forEach(particle => {
particle.draw(context)
particle.update()
})
}
connectParticles(context){
const maxDistance = 100
for(let a = 0; a < this.particles.length; a++){
for(let b = a; b < this.particles.length; b++) {
const dx = this.particles[a].x - this.particles[b].x
const dy = this.particles[a].y - this.particles[b].y
// pythagore
const distance = Math.hypot(dx, dy)
if (distance < maxDistance){
context.save()
const opacity = 1 - (distance/maxDistance)
context.globalAlpha = opacity
context.beginPath()
context.moveTo(this.particles[a].x, this.particles[a].y)
context.lineTo(this.particles[b].x, this.particles[b].y)
context.stroke()
context.restore()
}
}
}
}
}
const effect = new Effect(canvas)
//console.log(effect)
function animate(){
ctx.clearRect(0, 0, canvas.width, canvas.height)
effect.handleParticles(ctx)
requestAnimationFrame(animate)
}
animate()