From 0320a74012f609ac3c975570684b0b09bcdd5f75 Mon Sep 17 00:00:00 2001 From: sfja Date: Tue, 14 Oct 2025 23:14:35 +0200 Subject: [PATCH] cache image sprites --- src/gamelib.js | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/gamelib.js b/src/gamelib.js index cdcf6b5..eb20d3e 100644 --- a/src/gamelib.js +++ b/src/gamelib.js @@ -21,6 +21,7 @@ export class Gamelib { this.mouseUpHandlers = new Map(); this.mouseX = null; this.mouseY = null; + this.spriteCache = new Map(); } init() { @@ -107,11 +108,26 @@ export class Gamelib { drawSprite(x, y, width, height, name) { 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(); image.src = this.assetProvider.url(name); 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? }; }