-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
100 lines (90 loc) · 2.92 KB
/
script.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
let canvas;
let ctx;
let flowField;
let flowFieldAnimation;
window.onload = function(){
canvas = document.getElementById('canvas1');
ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
flowField = new FlowFieldEffect(ctx, canvas.width, canvas.height);
flowField.animate(0);
}
window.addEventListener('resize', function(){
cancelAnimationFrame(flowFieldAnimation);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
flowField = new FlowFieldEffect(ctx, canvas.width, canvas.height);
flowField.animate(0);
});
const mouse = {
x: 0,
y: 0
}
window.addEventListener('mousemove', function(e){
mouse.x = e.x;
mouse.y = e.y;
// console.log(e)
});
class FlowFieldEffect {
#ctx;
#width;
#height;
constructor(ctx, width, height){
this.#ctx = ctx;
this.#ctx.lineWidth = 0.75;
this.#width = width;
this.#height = height;
this.angle = 0;
this.lastTime = 0;
this.interval = 1000/60;
this.timer = 0;
this.cellSize = 10;
this.gradient;
this.#createGradient();
this.#ctx.strokeStyle = this.gradient;
this.angle;
this.radius = 0;
this.vr = 0.03;
}
#createGradient(){
this.gradient = this.#ctx.createLinearGradient(0, 0, this.#width, this.#height);
this.gradient.addColorStop("0.1", "#ff5c33");
this.gradient.addColorStop("0.2", "#ff66b3");
this.gradient.addColorStop("0.4", "#ccccff");
this.gradient.addColorStop("0.6", "#b3ffff");
this.gradient.addColorStop("0.8", "#80ff80");
this.gradient.addColorStop("0.9", "#ffff33");
}
#drawLine(angle, x, y){
let positionX = x;
let positionY = y;
let dx = mouse.x - positionX;
let dy = mouse.y - positionY;
let distance = dx * dx + dy * dy;
let length = distance * 0.00005;
this.#ctx.beginPath();
this.#ctx.moveTo(x, y);
this.#ctx.lineTo(x + Math.cos(angle) * length, y + Math.sin(angle) * length);
this.#ctx.stroke();
}
animate(timeStamp){
const deltaTime = timeStamp - this.lastTime;
this.lastTime = timeStamp;
if (this.timer > this.interval) {
this.#ctx.clearRect(0, 0, this.#width, this.#height);
this.radius += this.vr;
if (this.radius > 5 || this.radius < -5) this.vr *= -1;
for (let y = 0; y < this.#height; y += this.cellSize){
for (let x = 0; x < this.#width; x += this.cellSize){
const angle = (Math.cos(x * 0.01) + Math.sin(y * 0.01)) * this.radius;
this.#drawLine(angle, x, y);
}
}
this.timer = 0;
} else {
this.timer += deltaTime;
}
flowFieldAnimation = requestAnimationFrame(this.animate.bind(this));
}
}