diff options
Diffstat (limited to 'src/render/graphics.js')
-rw-r--r-- | src/render/graphics.js | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/src/render/graphics.js b/src/render/graphics.js new file mode 100644 index 0000000..de98633 --- /dev/null +++ b/src/render/graphics.js @@ -0,0 +1,47 @@ +// Pretty much a copy of my centipede code +game.graphics = ( + (context) => { + context.imageSmoothingEnabled = false; + const clear = () => { + context.clearRect(0, 0, game.width, game.height); + }; + + // Maybe this should be a component? + const Sprite = ({image, spriteX, spriteY, spriteWidth, spriteHeight, timePerFrame, cols, rows, numFrames, drawFunction}) => { + timePerFrame = timePerFrame ?? 100; + numFrames = numFrames ?? 1; + cols = cols ?? numFrames; + rows = rows ?? 1; + spriteX = spriteX ?? 0; + spriteY = spriteY ?? 0; + + let currentFrame = 0; + let lastTime = performance.now(); + + let draw; + if (!drawFunction) { + draw = (_elapsedTime, {x, y, rot, width, height}) => { + if (numFrames > 1) { + if (performance.now()-lastTime > timePerFrame) { + lastTime = performance.now(); + currentFrame = (currentFrame + 1) % numFrames; + } + } + context.save(); + context.translate(x+width/2, y+height/2); + context.rotate(rot * Math.PI / 180); + context.translate(-x-width/2, -y-height/2); + const row = currentFrame % rows; + const col = Math.floor(currentFrame / rows); + context.drawImage(image, spriteX+col*spriteWidth, spriteY+row*spriteHeight, spriteWidth, spriteHeight, x, y, width, height); + context.restore(); + }; + } else { + draw = (elapsedTime, drawSpec) => drawFunction(elapsedTime, drawSpec, context); + } + return { draw }; + } + + return { clear, Sprite }; + } +)(document.getElementById("game-canvas").getContext("2d"));
\ No newline at end of file |