cache image sprites
This commit is contained in:
parent
70ea49eac8
commit
0320a74012
@ -21,6 +21,7 @@ export class Gamelib {
|
|||||||
this.mouseUpHandlers = new Map();
|
this.mouseUpHandlers = new Map();
|
||||||
this.mouseX = null;
|
this.mouseX = null;
|
||||||
this.mouseY = null;
|
this.mouseY = null;
|
||||||
|
this.spriteCache = new Map();
|
||||||
}
|
}
|
||||||
|
|
||||||
init() {
|
init() {
|
||||||
@ -107,11 +108,26 @@ export class Gamelib {
|
|||||||
|
|
||||||
drawSprite(x, y, width, height, name) {
|
drawSprite(x, y, width, height, name) {
|
||||||
const cx = this.cx;
|
const cx = this.cx;
|
||||||
|
const spriteId = `${name}_${width}x${height}`;
|
||||||
|
|
||||||
|
if (this.spriteCache.has(spriteId)) {
|
||||||
|
const sprite = this.spriteCache.get(spriteId);
|
||||||
|
cx.drawImage(sprite, x, y);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// start by caching an empty canvas
|
||||||
|
const canvas = new OffscreenCanvas(width, height);
|
||||||
|
this.spriteCache.set(spriteId, canvas);
|
||||||
|
|
||||||
const image = new Image();
|
const image = new Image();
|
||||||
image.src = this.assetProvider.url(name);
|
image.src = this.assetProvider.url(name);
|
||||||
image.onload = () => {
|
image.onload = () => {
|
||||||
cx.drawImage(image, x, y, width, height);
|
const sprite = this.spriteCache.get(spriteId);
|
||||||
|
const spriteCx = sprite.getContext("2d");
|
||||||
|
spriteCx.drawImage(image, 0, 0);
|
||||||
|
|
||||||
|
// does it make sense to draw post fectum?
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user