-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
278 lines (226 loc) · 8.29 KB
/
main.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
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
/* Most of the code below is written in ES6 modules
* But some (specifically, data processing and config) can't be
* for node.js compatibility
* Hence, this has ended up as a cursed mixture of the two
* that I can't and won't fix.
*/
import initScroller from './src/scroller/wrapper.js';
import initStats from './src/stats.js';
import responsiveCanvas from './src/canvas.js';
let stats = initStats();
const COLORS = config.colors;
const SIZE = config.size;
// For ios safari. This has to be done before the canvas is created
document.getElementById('canvas-container').style.height = `${window.innerHeight - 60}px`;
const displayCanvas = responsiveCanvas(1024, 1024, document.getElementById("canvas-container"));
displayCanvas.id = "canvas";
const displayCtx = displayCanvas.getContext("2d");
displayCtx.imageSmoothingEnabled = false;
// Canvas that is drawn on
const canvas = document.createElement('canvas');
canvas.width = canvas.height = SIZE;
const ctx = canvas.getContext("2d");
ctx.imageSmoothingEnabled = false;
ctx.fillStyle = "white";
ctx.fillRect(0, 0, SIZE, SIZE);
window.showModal = (elem, bool) => (typeof elem == "string" ? document.getElementById(elem) : elem).style.display = bool ? "block" : "none";
window.updateStats = stats.update;
// For checking whether the mouse has moved
let dx = 0, dy = 0
let data = Array(SIZE).fill(0).map(() => Array(SIZE).fill(config.background));
const buttons = document.getElementById("buttons");
const timer = document.getElementById("timer");
const toggle = document.getElementById("toggle");
// WHYY, firefox
if(!toggle.checked) toggle.click();
let place = true;
let lastClick = 0, drawColor = 'black';
let playerCount, ws;
let reflow = () => {
document.getElementById('canvas-container').style.height = `${window.innerHeight - 60}px`;
scroller.setDimensions(parseInt(displayCanvas.style.width), parseInt(displayCanvas.style.height), parseInt(displayCanvas.style.width), parseInt(displayCanvas.style.height));
displayCanvas.resize();
}
window.addEventListener('resize', reflow);
let zoom = {
left: 0, top: 0, zoom: 1
};
let updateDisplay = () => {
displayCtx.clearRect(0, 0, 1024, 1024);
let canvasSize = parseInt(displayCanvas.style.width);
let left = zoom.left / zoom.z / (canvasSize / SIZE)
let top = zoom.top / zoom.z / (canvasSize / SIZE)
let size = SIZE / zoom.z
displayCtx.drawImage(canvas,
left, top, size, size,
0, 0, 1024, 1024);
}
let drawRect = (x, y, color) => {
ctx.fillStyle = color;
ctx.fillRect(x, y, 1, 1)
data[y][x] = COLORS.indexOf(color)
}
let render = (data) => {
for (let y in data) {
for(let x in data[y]) {
drawRect(x, y, COLORS[data[y][x]]);
}
}
updateDisplay();
}
let updatePos = () => {
sessionStorage.setItem('pos', JSON.stringify({...zoom, drawColor}))
}
// Initialize Scroller
let scroller = initScroller(updateDisplay, x => {
zoom = x;
updatePos();
}, displayCanvas, document)
if (sessionStorage.getItem('pos')) {
zoom = JSON.parse(sessionStorage.getItem('pos'));
let {z, top, left, color} = zoom;
drawColor = color;
scroller.zoomTo(z);
scroller.scrollTo(left, top);
}
// Dynamic button generation go brr
for (let color of COLORS) {
const button = document.createElement("button");
button.classList.add('color-button')
button.style.backgroundColor = color;
button.addEventListener("click", () => {
drawColor = color;
for(let button of buttons.childNodes) {
button.classList.remove('active')
}
button.classList.add('active')
});
buttons.appendChild(button);
}
buttons.childNodes[config.defaultSelected].click();
let startCountdown = () => {
let time = Date.now() - lastClick;
timer.style.display = "block";
if (time > config.delay * 1000) {
timer.textContent = "";
timer.style.display = "none";
return;
}
timer.textContent = (config.delay - time / 1000).toFixed(2);
setTimeout(startCountdown, 20);
}
window.downloadPNG = () => {
var link = document.createElement('a');
link.download = `canvas.png`;
link.href = canvas.toDataURL('png');
link.click();
}
displayCanvas.addEventListener('contextmenu', event => {
event.preventDefault();
if (displayCanvas.x < 1024 && displayCanvas.y > 0
&& displayCanvas.y < 1024 && displayCanvas.x > 0) {
buttons.childNodes[data[y()][x()]].click();
}
});
let getTruePos = (relative, offset) => (relative * SIZE / 1024 + offset / (parseInt(displayCanvas.style.width) / SIZE)) / zoom.z | 0
let x = () => getTruePos(displayCanvas.x, zoom.left);
let y = () => getTruePos(displayCanvas.y, zoom.top);
// These event listeners bubble in weird orders.
displayCanvas.addEventListener('pointerdown', (event) => {
// We use clientX / clientY because it's a simple position check
dx = event.clientX;
dy = event.clientY;
})
displayCanvas.addEventListener('pointerup', (event) => {
if (
// Server handling
(!config.server || (navigator.onLine && ws.readyState == 1)) &&
// Timing and disabling
place && Date.now() - lastClick > config.delay * 1000
// Within bounds
&& displayCanvas.x < 1024 && displayCanvas.y > 0
&& displayCanvas.y < 1024 && displayCanvas.x > 0
// Mouse hasn't moved
&& (dx == event.clientX && dy == event.clientY
|| (dy == 0 && dx == 0))
// Not redrawing
&& data[y()][x()] != COLORS.indexOf(drawColor)
) {
lastClick = Date.now();
startCountdown();
drawRect(x(), y(), drawColor);
updateDisplay();
stats[config.iteration - 1][drawColor]++;
stats.update();
ws.send(JSON.stringify({
d: formatMessage(x(), y(), COLORS.indexOf(drawColor)).toString()
}));
}
})
let showCoords = () => {
let clamp = pos => Math.min(Math.max(pos, 0), SIZE - 1);
document.getElementById('coords').innerText = `(${clamp(x())}, ${clamp(y())})`;
}
window.addEventListener('pointerup', showCoords);
window.addEventListener('pointermove', showCoords);
window.addEventListener('pointerdown', showCoords);
window.addEventListener('keypress', () => {
if (displayCanvas.keys.c) {
toggle.click();
}
})
toggle.addEventListener('click', () => {
place = !place
})
let updateCount = () => document.getElementById('player-count').innerText = playerCount;
let id2 = window.localStorage.getItem("id2");
if (!id2) {
id2 = [...Array(8)].map(_ => (Math.random() * 20 + 16 | 0).toString(36)).join("");
window.localStorage.setItem("id2", id2);
}
var start_ws = () => {
ws = new WebSocket((config.local ? "ws://localhost:8080" : "wss://canvas.rto.run/ws") + "?id2=" + id2);
ws.onopen = () => {}
ws.onmessage = message => {
((data) => {
if ('d' in data) {
var {x, y, color} = decodeMessage(data.d);
drawRect(x, y, COLORS[color]);
updateDisplay();
}
if ('s' in data) {
playerCount = data.s;
updateCount();
}
if ('r' in data) { // Only in first request
render(decodeData(data.r));
data = decodeData(data.r)
playerCount = data.s;
updateCount();
document.getElementById('player-icon').style.display = 'block';
document.getElementById('player-count').style.display = 'block';
document.getElementById('loader').style.display = 'none';
return;
}
// Rickroll if too fast
if ('e' in data) location.href = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";
})(JSON.parse(message.data));
}
ws.onclose = () => {
document.getElementById('player-icon').style.display = 'none';
document.getElementById('player-count').style.display = 'none';
document.getElementById('loader').style.display = 'block';
setTimeout(start_ws, 2000);
}
}
if (config.server) {
start_ws()
} else {
// Avoid errors while doing nothing
ws = {
send(){}
}
document.getElementById('player-icon').style.display = 'block';
document.getElementById('player-count').style.display = 'block';
document.getElementById('loader').style.display = 'none';
}