-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
518 lines (416 loc) · 18.8 KB
/
Copy pathscript.js
File metadata and controls
518 lines (416 loc) · 18.8 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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
document.addEventListener("DOMContentLoaded", function () {
const divCollection = document.getElementById("canvas-collection-container");
const bgCanvas = document.getElementById("bgCanvas");
const bgCtx = bgCanvas.getContext("2d");
const canvas = document.getElementById("planetsCanvas");
const ctx = canvas.getContext("2d");
const overlayCanvas = document.getElementById("overlayCanvas");
const overlayCtx = overlayCanvas.getContext('2d', { willReadFrequently: true });
const paddingSide = 15;
let width = document.getElementById("table-of-contents").clientWidth - paddingSide * 2; // padding
let height = 1;
[divCollection, bgCanvas, canvas, overlayCanvas].forEach((c) => {
c.width = width;
c.height = height;
c.style.width = width + 'px';
c.style.height = height + 'px';
});
let CLOCK_RUN_TIME = 0;
// consts
const planetMinRadius = 25;
const planetMaxRadius = 32;
const planetTravelAngle = 3 * Math.PI / 4; // bottom left, as the 0, 0 of canvas is on top left
const planetHeadTrailNum = 8;
const planetHeadTrailAngleExpand = Math.PI / 4 // 90 in total
const planetHeadTrailMinAngle = 23 * Math.PI / 180;
const planetHeadTrailMaxAngle = 45 * Math.PI / 180;
const planetHeadTrailSegments = 6;
const planetHeadTrailAmplitude = 4;
const planetHeadTrailDistanceToAmplitude = 12;
const planetHeadTrailMinFrequency = 0.21;
const planetHeadTrailMaxFrequency = 0.24;
const planetHeadTrailDistanceToFrequency = 7000;
const planetHeadTrailInitLength = 10;
const planetHeadTrailExpectedLength = 2350;
const planetHeadTrailLengthIncreaseRate = 0.04;
const planetHeadTrailMinFadeRate = 0.14;
const planetHeadTrailMaxFadeRate = 0.16;
const planetHeadTrailColorEndDarkenRate = 0.01; // the samller the darker at the end
const planeHeadGlowAlpha = 0.8;
const planetHeadGlowGraidentInnerRadius = 0.09;
const planetHeadGlowGradientOuterRaidus = 1.17;
const planetFullGlowRaidus = 1.17;
const planetTailScale = 100;
// img and colors
const flagImages = [ // flags path
"https://upload.wikimedia.org/wikipedia/en/c/c3/Flag_of_France.svg",
"https://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg"
];
let imgLoaded = 0;
const headColors = [
"rgb(220, 180, 241)",
"rgb(236, 170, 170)",
]
const colorCompositions = [
[20, // SD
[1, "rgb(255, 0, 0)"], // p(1) part solid red
[1, "rgb(255, 255, 255)"],
[1, "rgb(0, 0, 255)"]
],
[50, // SD
[7, "rgb(255, 0, 0)"],
[10, "rgb(255, 255, 255)"],
[3, "rgb(0, 0, 255)"]
],
];
// arr
let planets = [];
// event
let cx = 0, cy = 0;
let rect = bgCanvas.getBoundingClientRect();
window.addEventListener("mousemove", mouseMove);
window.addEventListener("touchmove", mouseMove);
// mouse move --> cx, cy
function mouseMove(e) {
cx = Math.floor((e.touches ? e.touches[0].clientX : e.clientX) - rect.left); // no float edge handle
cy = Math.floor((e.touches ? e.touches[0].clientY : e.clientY) - rect.top);
}
// // // // start // // // //
let bgHeightExtend = 1;
drawBg() // draw on bg canvas
generate(); // this includes
// test preload bg
function drawBg() {
let bgSrc = "images/galaxy-HD.jpg";
var bgImg = new Image();
bgImg.crossOrigin = "Anonymous";
bgImg.onload = function() {
let canvasWidth = bgCanvas.width;
let scaleFactor = canvasWidth / this.width;
let newHeight = this.height * scaleFactor * bgHeightExtend;
bgCtx.drawImage(bgImg, 0, 0, canvasWidth, newHeight);
bgCtx.fillStyle = "rgba(0, 0, 0, 0.6)"; // darker fill
bgCtx.fillRect(0, 0, width, height);
}
bgImg.src = bgSrc;
}
function generate() {
for (let i = 0; i < flagImages.length; i++) {
let { pos, radius } = getInitPlanetPos();
let flagImg = new Image();
flagImg.src = flagImages[i];
flagImg.crossOrigin = "anonymous";
planets.push({
// static
centerPos: pos,
radius: radius,
flag: flagImg,
colorComposition: colorCompositions[i],
headGlow: headColors[i].replace("rgb", "rgba").replace(")", `, ${planeHeadGlowAlpha})`), // rbg -> rgba
// dynamic
curPos: pos,
curHead: [],
curTail: []
});
imgLoaded++;
flagImg.onerror = () => console.error(`Failed to load image: ${flagImages[i]}`);
if (imgLoaded === flagImages.length) step();
}
}
function getInitPlanetPos() {
let pos;
let radius = getRandomIntFromRange(planetMinRadius, planetMaxRadius);
do {
pos = {
x: getRandomFromRange(radius, width - radius),
y: getRandomFromRange(radius, height - radius),
};
} while (planets.some(c => Math.hypot(c.centerPos.x - pos.x, c.centerPos.y - pos.y) < 2 * radius));
return { pos, radius };
}
function step() {
CLOCK_RUN_TIME += 1;
update();
render();
requestAnimationFrame(step);
}
function update() {
CLOCK_RUN_TIME += 1;
planets.forEach(planet => {
updateHeadTrailPos(planet);
//updateTailTrailPos(planet);
});
}
function updateHeadTrailPos(planet) {
if (planet.curHead.length < planetHeadTrailNum) {
let rep = planetHeadTrailNum - planet.curHead.length;
for (var i = 0; i < rep; i++) {
let alpha = getRandomFromRange(0.7, 1);
let color = getColorFromComposition(planet.colorComposition);
let curLength = planetHeadTrailInitLength;
let angle = getRandomFromRange(planetHeadTrailMinAngle, planetHeadTrailMaxAngle)
let firstDirection = getRandomFromRange(-planetTravelAngle - planetHeadTrailAngleExpand, -planetTravelAngle + planetHeadTrailAngleExpand - angle);
let secondDirection = firstDirection + angle;
let points = [];
for (var j = 0; j < planetHeadTrailSegments; j++) {
points.push(j * planetHeadTrailInitLength / planetHeadTrailSegments);
}
let amplitude = planetHeadTrailAmplitude;
let frequency = getRandomFromRange(planetHeadTrailMinFrequency, planetHeadTrailMaxFrequency);
let phase = getRandomIntFromRange(0, Math.PI * 2);
planet.curHead.push([alpha, color, curLength, firstDirection, secondDirection, points, amplitude, frequency, phase])
}
}
planet.curHead.forEach(trail => {
trail[0] -= getRandomFromRange(planetHeadTrailMinFadeRate, planetHeadTrailMaxFadeRate); // fade
let prevLength = trail[2];
let distanceExpanded = (planetHeadTrailExpectedLength - trail[2]) * planetHeadTrailLengthIncreaseRate;
trail[2] += distanceExpanded;
for (let i = 0; i < trail[5].length; i++) {
trail[5][i] = trail[2] * trail[5][i] / prevLength;
}
});
planet.curHead = planet.curHead.filter(trail => trail[0] > 0);
}
function render(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
overlayCtx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height);
planets.forEach(planet => {
let {x, y} = planet.curPos;
let radius = planet.radius;
let img = planet.flag;
drawSphere(img, x, y, radius);
drawLightShadow(planet);
drawHead(planet);
//drawTail(planet);
});
}
function drawSphere(img, x, y, radius) {
drawFlag(img, x, y, radius);
drawOverlaySphere(x, y, radius);
}
function drawFlag(img, x, y, radius) {
ctx.save();
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.clip();
ctx.drawImage(img, x - radius, y - radius, radius * 2, radius * 2);
ctx.fillStyle = "rgba(0, 0, 0, 0.5)";
ctx.fillRect(x - radius, y - radius, radius * 2, radius * 2);
ctx.restore();
}
function drawOverlaySphere(x, y, radius) {
var size = radius * 2,
zoom = 1;
overlayCtx.drawImage(
canvas,
x - canvas.offsetLeft - .5 * size / zoom,
y - canvas.offsetTop - .5 * size / zoom,
size / zoom,
size / zoom,
x - radius,
y - radius,
size,
size
);
var imgData = overlayCtx.getImageData(x - radius, y - radius, size, size);
pixels = imgData.data,
pixelsCopy = [], index = 0, h = size, w = size;
for (var i = 0; i <= pixels.length; i+=4) {
pixelsCopy[index] = [pixels[i], pixels[i+1], pixels[i+2], pixels[i+3]];
index++;
}
var result = fisheye(pixelsCopy, w, h);
for(var i = 0; i < result.length; i++) {
index = 4*i;
if (result[i] != undefined) {
pixels[index + 0] = result[i][0];
pixels[index + 1] = result[i][1];
pixels[index + 2] = result[i][2];
pixels[index + 3] = result[i][3];
}
}
overlayCtx.putImageData(imgData, x - radius, y - radius);
}
function fisheye(srcpixels, w, h) {
var dstpixels = srcpixels.slice(); // seperate
for (var y = 0; y < h; y++) { // row
var ny = ((2*y)/h)-1; // hor dis to center
var ny2 = ny*ny; // quadratic push
for (var x = 0; x < w; x++) { // col
var nx = ((2*x)/w)-1; // same here
var nx2 = nx*nx;
var r = Math.sqrt(nx2+ny2); // dis from center
if (0.0 <= r && r <= 1) { // check if out boudanary
var nr = Math.sqrt(1.0-r*r); // reverse
nr = (r + (1.0-nr)) / 2.0;
if (nr <= 1.0) {
var theta = Math.atan2(ny,nx); // angle
var nxn = nr*Math.cos(theta);
var nyn = nr*Math.sin(theta);
var x2 = parseInt(((nxn+1)*w)/2); // convert
var y2 = parseInt(((nyn+1)*h)/2);
var srcpos = parseInt(y2*w+x2);
if (srcpos >= 0 & srcpos < w*h) {
dstpixels[parseInt(y*w+x)] = srcpixels[srcpos];
}
}
}
}
}
return dstpixels;
}
function drawLightShadow(planet) {
let { x, y } = planet.curPos;
let radius = planet.radius;
x += 0;
overlayCtx.save();
overlayCtx.globalCompositeOperation = "brighter";
let color = planet.headGlow;
let lightGradient = overlayCtx.createRadialGradient(
x + radius * Math.cos(planetTravelAngle), y + radius * Math.sin(planetTravelAngle), radius * planetHeadGlowGraidentInnerRadius,
x, y, radius * planetHeadGlowGradientOuterRaidus
);
lightGradient.addColorStop(0, color);
lightGradient.addColorStop(1, "rgba(255, 165, 0, 0)");
overlayCtx.fillStyle = lightGradient;
overlayCtx.beginPath();
overlayCtx.arc(x, y, radius * planetFullGlowRaidus, 0, Math.PI * 2);
overlayCtx.fill();
}
function drawHead(planet) {
let { x, y } = planet.curPos;
let radius = planet.radius;
planet.curHead.forEach(trail => {
let alpha = trail[0];
let color = trail[1];
let curLength = trail[2];
let firstAngle = trail[3];
let secondAngle = trail[4];
let points = trail[5];
let amplitude = trail[6];
let frequency = trail[7];
let phase = trail[8];
// two points on the circle, use the other angle for expansion
let firstX = x + radius * Math.cos(secondAngle) * planetFullGlowRaidus;
let firstY = y - radius * Math.sin(secondAngle) * planetFullGlowRaidus;
let secondX = x + radius * Math.cos(firstAngle) * planetFullGlowRaidus;
let secondY = y - radius * Math.sin(firstAngle) * planetFullGlowRaidus;
let coordinatesX = [], coordinatesY = []; // the list for all the points iterating
coordinatesX.push(firstX);
coordinatesY.push(firstY);
for (var i = 0; i < points.length; i++) { // push the points along the line + point scaled to total distance and in sine, the further the point, the more overall amplitude and frequency (more up and downs)
coordinatesX.push(firstX - Math.cos(firstAngle) * points[i] + planetHeadTrailDistanceToAmplitude * points[i] / curLength * getValueFromSin(amplitude, frequency, (phase + planetHeadTrailDistanceToFrequency * points[i] / curLength)));
coordinatesY.push(firstY + Math.sin(firstAngle) * points[i] + planetHeadTrailDistanceToAmplitude * points[i] / curLength * getValueFromSin(amplitude, frequency, (phase + planetHeadTrailDistanceToFrequency * points[i] / curLength)));
}
for (var i = points.length - 1; i >= 0; i--) { // back iteration, the curve would be draw form the first angle (left) to second (right)
coordinatesX.push(secondX - Math.cos(secondAngle) * points[i] + planetHeadTrailDistanceToAmplitude * points[i] / curLength * getValueFromSin(amplitude, frequency, (phase + planetHeadTrailDistanceToFrequency * points[i] / curLength)));
coordinatesY.push(secondY + Math.sin(secondAngle) * points[i] + planetHeadTrailDistanceToAmplitude * points[i] / curLength * getValueFromSin(amplitude, frequency, (phase + planetHeadTrailDistanceToFrequency * points[i] / curLength)));
}
coordinatesX.push(secondX); // second start (the end)
coordinatesY.push(secondY);
coordinatesX.push(firstX); // link back to the first point
coordinatesY.push(firstY);
console.log(coordinatesX);
// create shrink effect:
let pushStrength = radius / 400;
for (let i = 0; i < coordinatesX.length; i++) {
let { pointX, pointY } = pushPointToPlanetEdge({ x, y }, radius, { pointX: coordinatesX[i], pointY: coordinatesY[i] }, pushStrength);
coordinatesX[i] = pointX;
coordinatesY[i] = pointY;
}
console.log(coordinatesX);
// bounding box
let minX = Math.min(...coordinatesX);
let minY = Math.min(...coordinatesY);
let maxX = Math.max(...coordinatesX);
let maxY = Math.max(...coordinatesY);
let colorValues = color.match(/[\d.]+/g).map(Number);
let r = Math.round(colorValues[0] || 0);
let g = Math.round(colorValues[1] || 0);
let b = Math.round(colorValues[2] || 0);
let startColor = `rgba(${r}, ${g}, ${b}, ${alpha})`;
r = darkenColor(r, planetHeadTrailColorEndDarkenRate);
g = darkenColor(g, planetHeadTrailColorEndDarkenRate);
b = darkenColor(b, planetHeadTrailColorEndDarkenRate);
let endColor = `rgba(${r}, ${g}, ${b}, 0)`;
let gradient = overlayCtx.createLinearGradient(minX, maxY, maxX, minY);
gradient.addColorStop(0, startColor);
gradient.addColorStop(1, endColor);
overlayCtx.save();
overlayCtx.fillStyle = gradient;
overlayCtx.beginPath();
overlayCtx.moveTo(coordinatesX[0], coordinatesY[0]);
for (var i = 0; i < coordinatesX.length - 1; i++) {
let ctrlX = (coordinatesX[i] + coordinatesX[i + 1]) / 2;
let ctrlY = (coordinatesY[i] + coordinatesY[i + 1]) / 2;
overlayCtx.quadraticCurveTo(coordinatesX[i], coordinatesY[i], ctrlX, ctrlY);
}
overlayCtx.fill();
overlayCtx.restore();
});
}
function getColorFromComposition(composition) {
let SD = composition[0];
let totalWeight = 0; // total parts
for (let i = 1; i < composition.length; i++) {
totalWeight += composition[i][0];
}
let randomValue = Math.random() * totalWeight; // selection
let chosenColor;
for (let i = 1; i < composition.length; i++) {
randomValue -= composition[i][0];
if (randomValue <= 0) {
chosenColor = composition[i][1];
break;
}
}
let match = chosenColor.match(/\d+/g);
let r = parseInt(match[0]);
let g = parseInt(match[1]);
let b = parseInt(match[2]);
r += randomGaussian(SD);
g += randomGaussian(SD);
b += randomGaussian(SD);
r = Math.max(0, Math.min(255, r));
g = Math.max(0, Math.min(255, g));
b = Math.max(0, Math.min(255, b));
return `rgb(${r}, ${g}, ${b})`;
}
function darkenColor(value, rate) {
return (Math.round(value * rate));
}
function getRandomFromRange(min, max) {
return min + Math.random() * (max - min);
}
function getRandomIntFromRange(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function randomGaussian(sd) {
let u = 1 - Math.random();
let v = 1 - Math.random();
let z = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
return z * sd;
}
function getValueFromSin(amplitude, frequency, phase) {
return amplitude * Math.sin(frequency * (CLOCK_RUN_TIME + phase))
}
function pushPointToPlanetEdge(planetPos, radius, pointPos, strength) {
let { planetX, planetY } = planetPos;
let { pointX, pointY } = pointPos;
let dx = planetX - pointX;
let dy = planetY - pointY;
let distSq = dx * dx + dy * dy + 0.001;
let dist = Math.sqrt(distSq);
let newDist;
if (dist > radius) {
newDist = radius + (dist - radius) * (1 - strength);
} else {
newDist = dist + (radius - dist) * strength;
}
let ratio = newDist / dist;
let newX = planetX - dx * ratio;
let newY = planetY - dy * ratio;
return { pointX: newX, pointY: newY };
}
});