-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
122 lines (78 loc) · 2.51 KB
/
Copy pathindex.js
File metadata and controls
122 lines (78 loc) · 2.51 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
const canvas = document.getElementById('app'),
ctx = canvas.getContext('2d'),
pointsInput = document.getElementById('points'),
colorizeInput = document.getElementById('color');
function registerEventListeners() {
pointsInput.addEventListener('input', () => redrawCanvas());
colorizeInput.addEventListener('input', () => redrawCanvas());
onresize = () => redrawCanvas();
}
function init() {
redrawCanvas();
registerEventListeners();
}
function redrawCanvas() {
const n = getNValue();
resetCanvas();
connectAllPoints(
getPointsForN(n)
);
}
function getNValue() {
const n = parseInt(pointsInput.value, 10);
document.getElementById('points-label').innerText = `${n}`;
return n;
}
function resetCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function getCanvasCenter() {
return { x: canvas.width / 2, y: canvas.height / 2 };
}
function connectAllPoints(points) {
points.forEach((point, idx) => {
ctx.strokeStyle = getColor(idx/points.length, points.length);
points.forEach((otherPoint, otherIdx) => {
ctx.beginPath();
ctx.moveTo(point.x, point.y);
ctx.lineTo(otherPoint.x, otherPoint.y);
ctx.stroke();
});
});
}
// Adjusted slightly from http://boltkey.cz/graph
function getColor(rat, n) {
const radius = getCircleRadius();
const a = Math.max(0.03, Math.min(1, (radius * 2 / 80000) * Math.max(1, 5 * (-Math.sqrt(n * 0.5) + 10))));
if (!colorizeInput.checked) {
return `rgba(255, 255, 255, ${a})`;
}
const r = Math.max(0, Math.min(255, 255 - Math.floor(Math.abs(256 - 768 * rat))));
const g = Math.max(0, Math.min(255, 255 - Math.floor(Math.abs(512 - 768 * rat))));
const b = Math.max(0, Math.min(255, Math.floor(Math.abs(384 - 768 * rat)) - 768/6));
return `rgba(${r}, ${g}, ${b}, ${a})`;
}
function getPointsForN(n) {
const points = [],
center = getCanvasCenter(),
segmentAngleRadian = 2 * Math.PI / n,
circleRadius = getCircleRadius();
for (let i = 1; i <= n; i++) {
points.push({
x: center.x + circleRadius * Math.cos(i * segmentAngleRadian),
y: center.y + circleRadius * Math.sin(i * segmentAngleRadian)
});
}
return points;
}
function getCircleRadius() {
return canvas.width > canvas.height
? canvas.height / 2.25
: canvas.width / 2.25;
}
window.onload = () => init();