summaryrefslogtreecommitdiff
path: root/centipede/js/game/graphics.js
blob: 3a0d7f95cbd8a5f35974e7f81c74e0b1a4e304de (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
48
49
50
51
52
53
54
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"));