diff options
author | Lizzy Hunt <lizzy.hunt@usu.edu> | 2024-01-12 19:13:13 -0700 |
---|---|---|
committer | Lizzy Hunt <lizzy.hunt@usu.edu> | 2024-01-12 19:13:13 -0700 |
commit | 07670ef8afb5a273267ea7149d5f7eef02fdf66b (patch) | |
tree | 2d0c8e64936c7fa2588786f4af199abf1bb48a60 /centipede/js/game/graphics.js | |
parent | 3ac982dfa653f0eb7fbceeb1678a3cae93b512f4 (diff) | |
download | simponic.xyz-07670ef8afb5a273267ea7149d5f7eef02fdf66b.tar.gz simponic.xyz-07670ef8afb5a273267ea7149d5f7eef02fdf66b.zip |
add subprojects
Diffstat (limited to 'centipede/js/game/graphics.js')
-rw-r--r-- | centipede/js/game/graphics.js | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/centipede/js/game/graphics.js b/centipede/js/game/graphics.js new file mode 100644 index 0000000..3a0d7f9 --- /dev/null +++ b/centipede/js/game/graphics.js @@ -0,0 +1,55 @@ +game.graphics = ( + (context) => { + context.imageSmoothingEnabled = false; + const clear = () => { + context.clearRect(0, 0, game.width, game.height); + }; + + const Sprite = ({sheetSrc, spriteX, spriteY, spriteWidth, spriteHeight, timePerFrame, cols, rows, numFrames, drawFunction}) => { + timePerFrame = timePerFrame ?? 100; + numFrames = numFrames ?? 1; + cols = cols ?? numFrames; + rows = rows ?? 1; + + let ready = false; + + let image; + if (sheetSrc) { + image = new Image(); + image.src = sheetSrc; + image.onload = () => { ready = true; }; + } + + let currentFrame = 0; + let lastTime = performance.now(); + + let draw; + if (!drawFunction) { + draw = (_elapsedTime, {x, y, rot, width, height}) => { + + if (ready) { + 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, timePerFrame, numFrames }; + } + + return { clear, Sprite }; + } +)(document.getElementById("game-canvas").getContext("2d"));
\ No newline at end of file |