-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimageStrands.js
142 lines (108 loc) · 2.93 KB
/
imageStrands.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
const OFFSET_INCR = 0.1;
const NUM_PARTICLES = 10000;
const TRANSPARENCY = 50;
const SCALE = 10;
let COLS;
let ROWS;
let particles;
let flowField;
let image;
let fr;
function preload() {
image = loadImage('data/painting.jpg', function(){}, function(e) { console.log(e); });
}
function setup() {
createCanvas(image.width, image.height);
background(30);
image.loadPixels();
COLS = floor(width / SCALE);
ROWS = floor(height / SCALE);
particles = new Array(NUM_PARTICLES)
for (const i of Array(particles.length).keys()) {
particles[i] = new Particle();
}
flowField = new Array(COLS*ROWS);
fr = createP('');
}
class Particle {
constructor() {
this.pos = createVector(random(width), random(height));
this.vel = createVector(0, 0);
this.acc = createVector(0, 0);
this.maxSpeed = 2;
this.prevPos = this.pos.copy();
}
follow() {
const x = floor(this.pos.x / SCALE);
const y = floor(this.pos.y / SCALE);
const index = x + y * COLS;
const force = flowField[index];
this.applyForce(force);
}
update() {
this.follow();
this.prevPos = this.pos.copy();
this.vel.add(this.acc);
this.vel.limit(this.maxSpeed);
this.pos.add(this.vel);
this.acc.mult(0);
this.edges();
}
edges() {
if (this.pos.x > width) {
this.pos.x = 0;
this.prevPos = this.pos.copy();
}
if (this.pos.x < 0) {
this.pos.x = width;
this.prevPos = this.pos.copy();
}
if (this.pos.y > height) {
this.pos.y = 0;
this.prevPos = this.pos.copy();
}
if (this.pos.y < 0) {
this.pos.y = height;
this.prevPos = this.pos.copy();
}
}
applyForce(force) {
this.acc.add(force);
}
draw() {
push();
const index = (floor(this.pos.x) + floor(this.pos.y) * width) * 4;
stroke(
image.pixels[index+0],
image.pixels[index+1],
image.pixels[index+2],
TRANSPARENCY);
strokeWeight(1);
line(this.prevPos.x, this.prevPos.y, this.pos.x, this.pos.y);
pop();
}
}
let zOffset = 0;
function draw() {
let yOffset = 0;
for (const y of Array(ROWS).keys()) {
let xOffset = 0;
for (const x of Array(COLS).keys()) {
const index = x + y * COLS;
const angle = noise(xOffset, yOffset, zOffset) * TWO_PI;
const v = p5.Vector.fromAngle(angle);
v.setMag(2);
flowField[index] = v;
xOffset += OFFSET_INCR;
}
yOffset += OFFSET_INCR;
}
for (const particle of particles) {
particle.update();
particle.draw();
}
zOffset += OFFSET_INCR / 5;
if (frameCount % 5 == 0) {
fr.html('FPS: ' + floor(frameRate()));
}
}