-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsketch-03.js
105 lines (81 loc) · 2.19 KB
/
sketch-03.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
101
102
103
104
105
const canvasSketch = require('canvas-sketch');
const random = require('canvas-sketch-util/random')
const math = require('canvas-sketch-util/math')
const settings = {
dimensions: [ 1080, 2048 ],
animate: true
};
// const animate = () => {
// console.log('domestika');
// requestAnimationFrame(animate);
// }
// animate();
const sketch = ({context, width, height}) => {
const agents = [];
for(let i=0;i< 40; i++){
const x = random.range(0, width);
const y = random.range(0, height);
agents.push(new Agent(x, y));
}
console.log(agents)
return ({ context, width, height }) => {
context.fillStyle = 'white';
context.fillRect(0, 0, width, height);
for(let i=0; i< agents.length; i++) {
const agent= agents[i]
for (let j=i + 1; j < agents.length; j++){
const other = agents[j];
const dist = agent.pos.getDistance(other.pos);
if (dist > 300) continue;
context.lineWidth = math.mapRange(dist, 0, 200, 12, 1);
context.beginPath();
context.moveTo(agent.pos.x, agent.pos.y);
context.lineTo(other.pos.x,other.pos.y);
context.stroke();
}
}
agents.forEach(agent => {
agent.update();
agent.draw(context);
agent.bounce(width,height);
});
};
};
canvasSketch(sketch, settings);
class Vector{
constructor(x, y, radius){
this.x = x;
this.y = y;
this.radius = 10;
}
getDistance(v){
const dx = this.x - v.x;
const dy = this.y - v.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
class Agent {
constructor(x, y) {
this.pos = new Vector(x, y);
this.vel = new Vector(random.range(-1, 1), random.range(-1, 1));
this.radius = random.range(4, 12);
}
bounce(width, height){
if(this.pos.x <= 0 || this.pos.x >= width) this.vel.x*=-1;
if(this.pos.y <= 0 || this.pos.y >= height) this.vel.y*=-1;
}
update(){
this.pos.x += this.vel.x;
this.pos.y += this.vel.y;
}
draw(context) {
context.save();
context.translate(this.pos.x, this.pos.y);
context.lineWidth = 4;
context.beginPath();
context.arc(0,0, this.radius, 0 ,Math.PI * 2);
context.fill();
context.stroke();
context.restore();
}
}