-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
69 lines (58 loc) · 1.86 KB
/
utils.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
import { globals } from './globals.js';
import { state } from './state.js';
const uuid = () => {
let dt = new Date().getTime();
const u = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (dt + Math.random() * 16) % 16 | 0;
dt = Math.floor(dt / 16);
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
});
return u;
};
const generateColours = (n) => {
const s = chroma.scale('Spectral');
return s.colors(n);
};
const generateRandomColour = () => {
// Get a list of the currently used colours (including the background)
const colours = state.species.map((s) => s.colour);
colours.push(chroma('#000000'));
// Find the average contrast between all colours
const average = (newColour) =>
colours.reduce((p, c) => p + chroma.contrast(c, newColour), 0) /
colours.length;
let randomColour = chroma.random();
// Keep generating colours until it's above threshold
while (average(randomColour) < 7) {
randomColour = chroma.random();
}
return randomColour;
};
const colourCritters = (critters, colour) => {
critters.forEach((c) => {
const cc = new Path2D();
cc.arc(c.position.x, c.position.y, globals.collisionRadius, 0, 2 * Math.PI);
globals.ctx.fillStyle = colour;
globals.ctx.fill(cc);
});
};
const directionTowardsCritter = (c1, c2) =>
Math.atan((c2.position.y - c1.position.y) / (c2.position.x - c1.position.x));
const distanceBetweenCritters = (c1, c2) =>
Math.sqrt(
(c1.position.x - c2.position.x) ** 2 + (c1.position.y - c2.position.y) ** 2,
);
const degreesToRads = (degrees) => 2 * Math.PI * (degrees / 360);
const clearCanvas = () => {
globals.ctx.clearRect(0, 0, globals.canvasWidth, globals.canvasHeight);
};
export {
colourCritters,
degreesToRads,
clearCanvas,
generateRandomColour,
distanceBetweenCritters,
directionTowardsCritter,
generateColours,
uuid,
};