-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathneural-network.js
More file actions
92 lines (67 loc) · 2.1 KB
/
neural-network.js
File metadata and controls
92 lines (67 loc) · 2.1 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.getElementById('neural-network');
const ctx = canvas.getContext('2d');
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
class Neuron {
constructor(x, y) {
this.x = x;
this.y = y;
this.connections = [];
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, 2, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(229, 9, 20, 0.1)';
ctx.fill();
}
}
class Connection {
constructor(neuron1, neuron2) {
this.neuron1 = neuron1;
this.neuron2 = neuron2;
this.speed = Math.random() * 0.5 + 0.5;
this.offset = Math.random() * Math.PI * 2;
}
draw() {
const time = Date.now() * 0.001;
const alpha = Math.sin(time * this.speed + this.offset) * 0.1 + 0.1;
ctx.beginPath();
ctx.moveTo(this.neuron1.x, this.neuron1.y);
ctx.lineTo(this.neuron2.x, this.neuron2.y);
ctx.strokeStyle = `rgba(229, 9, 20, ${alpha})`;
ctx.lineWidth = 0.5;
ctx.stroke();
}
}
const neurons = [];
const connections = [];
const numNeurons = 50;
for (let i = 0; i < numNeurons; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
neurons.push(new Neuron(x, y));
}
for (let i = 0; i < neurons.length; i++) {
for (let j = i + 1; j < neurons.length; j++) {
if (Math.random() < 0.1) {
connections.push(new Connection(neurons[i], neurons[j]));
}
}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
neurons.forEach(neuron => {
neuron.x += (Math.random() - 0.5) * 0.5;
neuron.y += (Math.random() - 0.5) * 0.5;
neuron.x = Math.max(0, Math.min(canvas.width, neuron.x));
neuron.y = Math.max(0, Math.min(canvas.height, neuron.y));
});
connections.forEach(connection => connection.draw());
neurons.forEach(neuron => neuron.draw());
requestAnimationFrame(animate);
}
animate();