-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspritesheet.js
More file actions
32 lines (27 loc) · 891 Bytes
/
spritesheet.js
File metadata and controls
32 lines (27 loc) · 891 Bytes
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
class SpriteSheet {
constructor (src, spriteSize, loadedHandler) {
this.img = new Image();
this.spriteSize = spriteSize;
this.img.src = src;
this.img.addEventListener('load', this.loaded.bind(this));
this.loadedHandler = loadedHandler;
this.canvas = document.createElement('canvas');
this.ctx = this.canvas.getContext('2d');
this.cache = new Map();
}
loaded () {
console.log("sprite sheet loaded: " + this.img.src);
this.ctx.drawImage(this.img, 0, 0);
this.loadedHandler(this);
}
getSpriteImageData (spriteX, spriteY) {
const key = spriteX + '-' + spriteY;
if(this.cache.has(key)) {
return this.cache.get(key);
} else {
const data = this.ctx.getImageData(spriteX * this.spriteSize, spriteY * this.spriteSize, this.spriteSize, this.spriteSize);
this.cache.set(key, data);
return data;
}
}
}