-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanimator.js
More file actions
53 lines (46 loc) · 1.53 KB
/
animator.js
File metadata and controls
53 lines (46 loc) · 1.53 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
class Animator {
constructor(spritesheet,xStart, yStart, width, height, frameCount, frameDuration, framePadding, reverse, loop) {
Object.assign(this, { spritesheet,
xStart, yStart,
height, width,
frameCount, frameDuration, framePadding,
reverse, loop });
this.elapsedTime = 0;
this.totalTime = this.frameCount * this.frameDuration;
}
drawFrame(tick, ctx, x, y, scale) {
this.elapsedTime += tick;
if (this.isDone()) {
if (this.loop) {
this.elapsedTime -= this.totalTime;
} else {
return;
}
}
let frame = this.currentFrame();
if (this.reverse) {
ctx.save();
ctx.scale(-1, 1);
ctx.drawImage(this.spritesheet,
this.xStart, this.yStart + frame * (this.height + this.framePadding),
this.width, this.height,
-x - this.width * scale, y,
this.width * scale,
this.height * scale);
ctx.restore();
} else {
ctx.drawImage(this.spritesheet,
this.xStart, this.yStart + frame * (this.height + this.framePadding),
this.width, this.height,
x, y,
this.width * scale,
this.height * scale);
}
}
currentFrame() {
return Math.floor(this.elapsedTime / this.frameDuration);
}
isDone() {
return Math.floor(this.elapsedTime >= this.totalTime);
}
}