-
Notifications
You must be signed in to change notification settings - Fork 1
/
zoomtest.ts
412 lines (361 loc) · 9.08 KB
/
zoomtest.ts
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
import { emitter } from "@/composables/useEmit";
import type { User } from "@/types/general";
interface CharacterAnimation {
[key: string]: number[][];
}
const characterAnimations: CharacterAnimation = {
"walk-down": [
[0, 0],
[24, 1],
[48, 0],
],
"walk-left": [
[0, 24],
[24, 25],
[48, 24],
],
"walk-right": [
[0, 48],
[24, 49],
[48, 48],
],
"walk-up": [
[0, 72],
[24, 73],
[48, 72],
],
};
function loadImage(src: string): HTMLImageElement {
const image = new Image();
image.src = src;
return image;
}
function drawPlayer(
ctx: CanvasRenderingContext2D,
characterImg: HTMLImageElement,
animation: string,
frame: number,
player: User,
cameraX: number,
cameraY: number,
zoomFactor: number
) {
const frameCoords = characterAnimations[animation][frame];
ctx.drawImage(
characterImg,
frameCoords[0],
frameCoords[1],
24,
24,
player.x * zoomFactor - cameraX,
player.y * zoomFactor - cameraY,
96,
96
);
ctx.fillStyle = "white";
ctx.font = "20px Arial";
const userNameTextWidth = ctx.measureText(player.userName).width;
ctx.fillText(
player.userName,
player.x * zoomFactor - cameraX - userNameTextWidth / 24,
player.y * zoomFactor - cameraY - characterImg.height / 4 + 20
);
}
function updateAnimationFrame(
pressedKeys: { [key: string]: boolean },
animationState: string,
animationFrame: number,
animationTick: number
): [number, number] {
if (pressedKeys.w || pressedKeys.a || pressedKeys.s || pressedKeys.d) {
animationTick++;
} else {
animationFrame = 1;
}
if (animationTick >= 7) {
animationFrame++;
if (animationFrame >= characterAnimations[animationState].length) {
animationFrame = 0;
}
animationTick = 0;
}
return [animationFrame, animationTick];
}
export function createCanvasApp(
users: User[],
myPlayerId: string,
speed: number,
canvas: HTMLCanvasElement,
canvasFrameRate: number,
spaceMap: string,
myCharacterSprite: string,
initialSetupCompleted: boolean
) {
const ctx = canvas.getContext("2d")!;
const worldImg = loadImage(spaceMap);
const characterImg = loadImage(myCharacterSprite);
const characterImgMyPlayer = loadImage(myCharacterSprite);
let cameraX = 200;
let cameraY = 200;
let myPlayer: User = {
id: "",
userName: "",
x: 0,
y: 0,
characterSprite: "",
facingTo: "",
};
const pressedKeys = {
w: false,
a: false,
s: false,
d: false,
};
let zoomFactor = 1;
let lastPressedKey = "null";
let animationState = "walk-down";
let animationFrame = 0;
let animationTick = 0;
let lastTime = performance.now();
let fps = 0;
let refreshInterval = 1000 / canvasFrameRate;
const userAgent = navigator.userAgent;
const gameLoop = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Save the original canvas context state
ctx.save();
// Center camera on my player
myPlayer = users.find((user) => user.id === myPlayerId)!;
if (myPlayer) {
cameraX = myPlayer.x * zoomFactor - canvas.width / 2;
cameraY = myPlayer.y * zoomFactor - canvas.height / 2;
}
// Apply zoom and translation to the canvas context
ctx.scale(zoomFactor, zoomFactor);
ctx.translate(-cameraX / zoomFactor, -cameraY / zoomFactor);
// Draw world
ctx.drawImage(
worldImg,
0,
0,
worldImg.width,
worldImg.height,
-worldImg.height / 2,
-worldImg.width / 2,
worldImg.width,
worldImg.height
);
if (pressedKeys.w) {
myPlayer.y -= speed;
animationState = "walk-up";
}
if (pressedKeys.a) {
myPlayer.x -= speed;
animationState = "walk-left";
}
if (pressedKeys.s) {
myPlayer.y += speed;
animationState = "walk-down";
}
if (pressedKeys.d) {
myPlayer.x += speed;
animationState = "walk-right";
}
// Draw my player
drawPlayer(
ctx,
characterImgMyPlayer,
animationState,
animationFrame,
myPlayer,
cameraX / zoomFactor,
cameraY / zoomFactor,
zoomFactor
);
// Update animation frame
[animationFrame, animationTick] = updateAnimationFrame(
pressedKeys,
animationState,
animationFrame,
animationTick
);
// Draw other players
users.forEach((user) => {
if (user.id !== myPlayerId) {
drawPlayer(
ctx,
characterImg,
"walk-down",
1,
user,
cameraX / zoomFactor,
cameraY / zoomFactor,
zoomFactor
);
}
});
// Restore the original canvas context state
ctx.restore();
// Calculate FPS
const currentTime = performance.now();
const deltaTime = currentTime - lastTime;
lastTime = currentTime;
// Draw FPS
fps = Math.round(1000 / deltaTime);
ctx.fillStyle = "black";
// Bold Poppins 16px
ctx.font = "bold 16px Poppins";
ctx.fillText(`FPS: ${fps}`, 10, 20);
// Check the browser and use the appropriate fps limiter because every browser has its own way of doing it
if (userAgent.indexOf("Firefox") > -1) {
// FIXME: Can't limit fps in Firefox
requestAnimationFrame(gameLoop);
} else if (userAgent.indexOf("Chrome") > -1) {
setTimeout(gameLoop, refreshInterval);
} else {
setTimeout(gameLoop, refreshInterval);
}
};
if (
users.length > 0 &&
myPlayerId !== "" &&
speed !== 0 &&
spaceMap !== "" &&
initialSetupCompleted
) {
gameLoop();
} else {
const checkConditionsBeforeLoop = setInterval(() => {
if (
users.length > 0 &&
myPlayerId !== "" &&
speed !== 0 &&
spaceMap !== "" &&
initialSetupCompleted
) {
gameLoop();
clearInterval(checkConditionsBeforeLoop);
// Emit event to notify that the canvas is loaded
emitter.emit("canvasLoaded");
}
}, 0);
}
/******************
* KEYBOARD EVENTS *
******************/
canvas.addEventListener("keydown", (e: KeyboardEvent) => {
// TODO: Prevent diagonal movement
// Listen to both lower and upper case
switch (e.key.toLowerCase()) {
case "w":
pressedKeys.w = true;
lastPressedKey = "w";
break;
case "a":
pressedKeys.a = true;
lastPressedKey = "a";
break;
case "s":
pressedKeys.s = true;
lastPressedKey = "s";
break;
case "d":
pressedKeys.d = true;
lastPressedKey = "d";
break;
}
});
canvas.addEventListener("keyup", (e: KeyboardEvent) => {
switch (e.key.toLowerCase()) {
case "w":
pressedKeys.w = false;
break;
case "a":
pressedKeys.a = false;
break;
case "s":
pressedKeys.s = false;
break;
case "d":
pressedKeys.d = false;
break;
}
// Go back to the last key pressed after the second key is released
switch (lastPressedKey as string) {
case "w":
myPlayer.y -= speed;
animationState = "walk-up";
break;
case "a":
myPlayer.x -= speed;
animationState = "walk-left";
break;
case "s":
myPlayer.y += speed;
animationState = "walk-down";
break;
case "d":
myPlayer.x += speed;
animationState = "walk-right";
break;
}
// Only emit if key is w,a,s,d or W,A,S,D and after user has stopped moving
const validKeys = ["w", "a", "s", "d"];
if (validKeys.includes(e.key.toLocaleLowerCase())) {
// Emit player move event
emitter.emit("playerMove", myPlayer);
}
});
/******************
* MOUSE EVENTS *
******************/
// Listen to double click
/* canvas.addEventListener("dblclick", (e: MouseEvent) => {
const x = e.clientX + cameraX - 8;
const y = e.clientY + cameraY - 25;
// Emit double click event
emitter.emit("doubleClick", { x, y });
myPlayer.x = x;
myPlayer.y = y;
}); */
// Listen to right click
canvas.addEventListener("contextmenu", (e: MouseEvent) => {
const mouseX = e.clientX;
const mouseY = e.clientY;
const worldX = e.clientX + cameraX;
const worldY = e.clientY + cameraY;
const mousePos = {
mouseX,
mouseY,
};
const worldPos = {
worldX,
worldY,
};
// Emit right click event
emitter.emit("rightClick", { mousePos, worldPos });
e.preventDefault();
});
// Get right click move position confirmation
emitter.on("rightClickPlayerMoveConfirmed", async (user) => {
myPlayer.x = user.x - 36;
myPlayer.y = user.y - 64;
});
// Override zoom and ctrl+scroll
canvas.addEventListener("wheel", (e: WheelEvent) => {
if (e.ctrlKey) {
e.preventDefault();
const zoomSpeed = 0.1;
if (e.deltaY < 0) {
// Zoom in
// emitter.emit("zoomIn", zoomSpeed);
zoomFactor += zoomSpeed;
} else {
// Zoom out
//emitter.emit("zoomOut", zoomSpeed);
zoomFactor -= zoomSpeed;
}
zoomFactor = Math.min(Math.max(zoomFactor, 0.1), 5);
}
});
}