-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClientEngine.js
More file actions
77 lines (62 loc) · 1.81 KB
/
ClientEngine.js
File metadata and controls
77 lines (62 loc) · 1.81 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
/* eslint-disable object-curly-newline */
import EventSourceMixin from '../common/EventSourceMixin';
import ClientCamera from './ClientCamera';
import ClientInput from './ClientInput';
class ClientEngine {
constructor(canvas) {
Object.assign(this, {
canvas,
ctx: null,
imageLoaders: [],
sprites: {},
images: {},
camera: new ClientCamera({ canvas, engine: this.engine }),
input: new ClientInput(canvas),
});
this.ctx = canvas.getContext('2d');
this.loop = this.loop.bind(this);
}
start() {
this.loop();
}
loop(timestamp) {
const { ctx, canvas } = this;
ctx.fillStyle = 'black';
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.trigger('render', timestamp);
this.initNextFrame();
}
initNextFrame() {
window.requestAnimationFrame(this.loop);
}
loadSprites(spritesGroup) {
this.imageLoaders = [];
Object.keys(spritesGroup).forEach((groupName) => {
const group = spritesGroup[groupName];
this.sprites[groupName] = group;
Object.keys(group).forEach((spriteName) => {
const { img } = group[spriteName];
if (!this.images[img]) {
this.imageLoaders.push(this.loadImage(img));
}
});
});
return Promise.all(this.imageLoaders);
}
loadImage(url) {
return new Promise((resolve) => {
const i = new Image();
this.images[url] = i;
i.onload = () => resolve(i);
i.src = url;
});
}
renderSpriteFrame({ sprite, frame, x, y, w, h }) {
const spriteCfg = this.sprites[sprite[0]][sprite[1]];
const [fx, fy, fw, fh] = spriteCfg.frames[frame];
const img = this.images[spriteCfg.img];
this.ctx.drawImage(img, fx, fy, fw, fh, x, y, w, h);
}
}
Object.assign(ClientEngine.prototype, EventSourceMixin);
export default ClientEngine;