summaryrefslogtreecommitdiff
path: root/src/render/graphics.js
blob: aa4195e6164586abedba888e7232bbebb1c79210 (plain)
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Pretty much a copy of my centipede code
game.graphics = (
  (context) => {
    context.imageSmoothingEnabled = false;
    const clear = () => {
      context.clearRect(0, 0, game.canvas.width, game.canvas.height);
    };
    
    const Sprite = ({image, spriteX, spriteY, spriteWidth, spriteHeight, timePerFrame, cols, rows, numFrames, color, 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 };
  }
)(game.canvas.context);