-
Notifications
You must be signed in to change notification settings - Fork 0
/
sprite.js
84 lines (78 loc) · 1.84 KB
/
sprite.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
class Sprite {
constructor({
position,
imageSrc,
frameRate = 1,
animations,
frameBuffer = 2,
loop = true,
autoplay = true,
}) {
this.position = position;
this.image = new Image();
this.image.onload = () => {
this.loaded = true;
this.width = this.image.width / frameRate;
this.height = this.image.height;
};
this.image.src = imageSrc;
this.loaded = false;
this.frameRate = frameRate;
this.currentFrame = 0;
this.elapsedFrames = 0;
this.frameBuffer = frameBuffer;
this.animations = animations;
this.loop = loop;
this.autoplay = autoplay;
if (this.animations) {
for (let key in this.animations) {
const image = new Image();
image.src = this.animations[key].imageSrc;
this.animations[key].image = image;
}
}
}
draw() {
if (!this.loaded) return;
const cropbox = {
position: {
x: this.width * this.currentFrame,
y: 0,
},
width: this.width,
height: this.height,
};
c.drawImage(
this.image,
cropbox.position.x,
cropbox.position.y,
cropbox.width,
cropbox.height,
this.position.x,
this.position.y,
this.width,
this.height
);
this.updateFrames();
}
play() {
this.autoplay = true;
}
updateFrames() {
if (!this.autoplay) return;
this.elapsedFrames++;
if (this.elapsedFrames % this.frameBuffer === 0) {
if (this.currentFrame < this.frameRate - 1) this.currentFrame++;
else if (this.loop) this.currentFrame = 0;
}
if (this.currentAnimation?.onComplete) {
if (
this.currentFrame === this.frameRate - 1 &&
!this.currentAnimation.isActive
) {
this.currentAnimation.onComplete();
this.currentAnimation.isActive = true;
}
}
}
}