-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnakeground.js
More file actions
317 lines (277 loc) · 9.63 KB
/
snakeground.js
File metadata and controls
317 lines (277 loc) · 9.63 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
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/**
* snakeground.js
* Canvas animation - particles flowing left-to-right with double sine wave motion
*/
(function () {
"use strict";
// --- Shape generation ---
var EDGE_LEN = 14; // fixed distance between connected nodes
var NODE_RADIUS = 4;
var STROKE_WIDTH = 1.5;
var SHAPE_COLOR = "#3b82f6";
var MIN_ANGLE = Math.PI / 4; // 45 degrees
// get angles of all edges connected to nodeIdx
function edgeAngles(nodeIdx, nodes, edges) {
var angles = [];
for (var i = 0; i < edges.length; i++) {
var other = -1;
if (edges[i][0] === nodeIdx) other = edges[i][1];
else if (edges[i][1] === nodeIdx) other = edges[i][0];
if (other >= 0) {
angles.push(Math.atan2(
nodes[other].y - nodes[nodeIdx].y,
nodes[other].x - nodes[nodeIdx].x
));
}
}
return angles;
}
// check if candidate angle respects MIN_ANGLE from all existing angles
function angleOk(candidate, existing) {
for (var i = 0; i < existing.length; i++) {
var diff = Math.abs(candidate - existing[i]);
// normalize to [0, PI]
diff = diff % (Math.PI * 2);
if (diff > Math.PI) diff = Math.PI * 2 - diff;
if (diff < MIN_ANGLE) return false;
}
return true;
}
// pick a random angle that respects MIN_ANGLE, with retries
function pickAngle(rng, existing) {
for (var attempt = 0; attempt < 36; attempt++) {
var a = rng() * Math.PI * 2;
if (angleOk(a, existing)) return a;
}
// fallback: find largest gap and place in its center
if (existing.length === 0) return rng() * Math.PI * 2;
var sorted = existing.slice().sort(function (a, b) { return a - b; });
var bestGap = 0, bestMid = sorted[0];
for (var i = 0; i < sorted.length; i++) {
var next = i + 1 < sorted.length ? sorted[i + 1] : sorted[0] + Math.PI * 2;
var gap = next - sorted[i];
if (gap > bestGap) { bestGap = gap; bestMid = sorted[i] + gap / 2; }
}
return bestMid;
}
function generateShape(rng) {
var nodeCount = rng() < 0.5 ? 3 : 4;
var nodes = [{ x: 0, y: 0, filled: rng() < 0.5 }];
var edges = [];
for (var i = 1; i < nodeCount; i++) {
var parent = Math.floor(rng() * i);
var existing = edgeAngles(parent, nodes, edges);
var angle = pickAngle(rng, existing);
nodes.push({
x: nodes[parent].x + Math.cos(angle) * EDGE_LEN,
y: nodes[parent].y + Math.sin(angle) * EDGE_LEN,
filled: rng() < 0.5,
});
edges.push([parent, i]);
}
// optionally add 1 extra edge (respecting min angle at both ends)
if (nodeCount >= 3 && rng() < 0.4) {
var a = Math.floor(rng() * nodeCount);
var b = Math.floor(rng() * nodeCount);
if (a !== b) {
var dup = false;
for (var k = 0; k < edges.length; k++) {
if ((edges[k][0] === a && edges[k][1] === b) ||
(edges[k][0] === b && edges[k][1] === a)) { dup = true; break; }
}
if (!dup) {
var angA = Math.atan2(nodes[b].y - nodes[a].y, nodes[b].x - nodes[a].x);
var angB = angA + Math.PI;
if (angleOk(angA, edgeAngles(a, nodes, edges)) &&
angleOk(angB, edgeAngles(b, nodes, edges))) {
edges.push([a, b]);
}
}
}
}
// center the shape around (0,0)
var cx = 0, cy = 0;
for (var j = 0; j < nodes.length; j++) { cx += nodes[j].x; cy += nodes[j].y; }
cx /= nodes.length; cy /= nodes.length;
for (var j = 0; j < nodes.length; j++) { nodes[j].x -= cx; nodes[j].y -= cy; }
return { nodes: nodes, edges: edges };
}
// --- Drawing function ---
function drawCustom(ctx, shape, location_x, location_y, rotate) {
ctx.save();
ctx.translate(location_x, location_y);
ctx.rotate(rotate);
ctx.strokeStyle = SHAPE_COLOR;
ctx.fillStyle = SHAPE_COLOR;
ctx.lineWidth = STROKE_WIDTH;
// draw edges
for (var e = 0; e < shape.edges.length; e++) {
var a = shape.nodes[shape.edges[e][0]];
var b = shape.nodes[shape.edges[e][1]];
ctx.beginPath();
ctx.moveTo(a.x, a.y);
ctx.lineTo(b.x, b.y);
ctx.stroke();
}
// draw nodes — clear edge lines behind hollow circles first
for (var n = 0; n < shape.nodes.length; n++) {
var nd = shape.nodes[n];
if (!nd.filled) {
// erase the area behind the hollow circle
ctx.save();
ctx.beginPath();
ctx.arc(nd.x, nd.y, NODE_RADIUS + STROKE_WIDTH / 2, 0, Math.PI * 2);
ctx.globalCompositeOperation = "destination-out";
ctx.fill();
ctx.restore();
}
ctx.beginPath();
ctx.arc(nd.x, nd.y, NODE_RADIUS, 0, Math.PI * 2);
if (nd.filled) {
ctx.fill();
ctx.stroke();
} else {
ctx.stroke();
}
}
ctx.restore();
}
// --- Seeded RNG (mulberry32) ---
function mulberry32(seed) {
return function () {
seed |= 0;
seed = (seed + 0x6d2b79f5) | 0;
var t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// --- Global wave function: y is a function of x and global time ---
// All particles on the same x get the same y => they form a visible snake
function waveY(x, time, opts, baseY) {
var sin1 = Math.sin(x * opts.sinFrequency1 + time * opts.sinDrift1) * opts.sinAmplitude1;
var sin2 = Math.sin(x * opts.sinFrequency2 + time * opts.sinDrift2) * opts.sinAmplitude2;
return baseY + sin1 + sin2;
}
// Derivative of waveY w.r.t. x (for rotation / tangent direction)
function waveDY(x, time, opts) {
var dy =
Math.cos(x * opts.sinFrequency1 + time * opts.sinDrift1) * opts.sinAmplitude1 * opts.sinFrequency1 +
Math.cos(x * opts.sinFrequency2 + time * opts.sinDrift2) * opts.sinAmplitude2 * opts.sinFrequency2;
return dy;
}
// --- Default options ---
var defaults = {
particleSpacing: 60, // px between particles (determines count from width)
speed: 0.3, // horizontal px per frame
sinAmplitude1: 200, // small sine amplitude (px)
sinFrequency1: 0.002, // small sine spatial frequency (per px)
sinDrift1: 0.002, // small sine time drift speed
sinAmplitude2: 400, // large sine amplitude (px)
sinFrequency2: 0.0009, // large sine spatial frequency (per px)
sinDrift2: 0.0005, // large sine time drift speed
pageHeight: 0, // full scrollable page height (0 = auto from canvas)
};
// --- Particle class ---
function Particle(canvas, rng, opts, index, pageHeight) {
this.canvas = canvas;
this.opts = opts;
this.pageHeight = pageHeight;
this.shape = generateShape(rng);
var count = Math.max(1, Math.floor(canvas.width / opts.particleSpacing));
var spacing = canvas.width / count;
this.x = index * spacing;
}
Particle.prototype.update = function (time) {
var opts = this.opts;
// horizontal movement
this.x += opts.speed;
// y from global wave function — baseY is center of canvas (viewport)
this.y = waveY(this.x, time, opts, this.canvas.height * 0.5);
// rotation = tangent direction of the wave at this x
var dy = waveDY(this.x, time, opts);
this.rotate = Math.atan2(dy, 1);
// wrap: exit right → re-enter left
if (this.x > this.canvas.width + 20) {
this.x = -20;
}
};
Particle.prototype.draw = function (ctx) {
drawCustom(ctx, this.shape, this.x, this.y, this.rotate);
};
// --- Main controller ---
function Snakeground(canvas, userOpts) {
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this.opts = Object.assign({}, defaults, userOpts);
this.particles = [];
this.running = false;
this.rafId = null;
this.time = 0;
this._resize();
this._initParticles();
this._bindResize();
this.start();
}
Snakeground.prototype._getPageHeight = function () {
return this.opts.pageHeight || this.canvas.height;
};
Snakeground.prototype._resize = function () {
var parent = this.canvas.parentElement || document.body;
this.canvas.width = parent.clientWidth;
this.canvas.height = parent.clientHeight;
};
Snakeground.prototype._bindResize = function () {
var self = this;
var timer;
window.addEventListener("resize", function () {
clearTimeout(timer);
timer = setTimeout(function () {
self._resize();
}, 150);
});
};
Snakeground.prototype._initParticles = function () {
var rng = mulberry32(42);
var count = Math.max(1, Math.floor(this.canvas.width / this.opts.particleSpacing));
var ph = this._getPageHeight();
for (var i = 0; i < count; i++) {
this.particles.push(new Particle(this.canvas, rng, this.opts, i, ph));
}
};
Snakeground.prototype._loop = function () {
var ctx = this.ctx;
var w = this.canvas.width;
var h = this.canvas.height;
ctx.clearRect(0, 0, w, h);
this.time += 1;
for (var i = 0; i < this.particles.length; i++) {
this.particles[i].update(this.time);
this.particles[i].draw(ctx);
}
if (this.running) {
this.rafId = requestAnimationFrame(this._loop.bind(this));
}
};
Snakeground.prototype.start = function () {
if (!this.running) {
this.running = true;
this._loop();
}
};
Snakeground.prototype.stop = function () {
this.running = false;
if (this.rafId) {
cancelAnimationFrame(this.rafId);
this.rafId = null;
}
};
Snakeground.prototype.setPageHeight = function (h) {
this.opts.pageHeight = h;
for (var i = 0; i < this.particles.length; i++) {
this.particles[i].pageHeight = h;
}
};
// --- Public API ---
window.Snakeground = Snakeground;
})();