iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 9
1
Modern Web

以前端角度探討遊戲化的資訊設計系列 第 9

Day 09 - simple change direction

  • 分享至 

  • xImage
  •  

改變刺蝟的方向

Demo

(function() {
  var hedgehogImage, canvas;

  class sprite {
    constructor({
      context,
      width,
      height,
      image,
      ticksPerFrame,
      numberOfFrames
    }) {
      this.context = context;
      this.width = width;
      this.height = height;
      this.image = image;
      this.frameIndex = 0;
      this.tickCount = 0;
      this.ticksPerFrame = ticksPerFrame || 0;
      this.numberOfFrames = numberOfFrames || 1;

    }
    update = () => {
						// this.context.scale(-1, 1);

      this.tickCount += 1;
      if (this.tickCount > this.ticksPerFrame) {
        this.tickCount = 0;

        // If the current frame index is in range
        if (this.frameIndex < this.numberOfFrames - 1) {
          // Go to the next frame
          this.frameIndex += 1;
        } else {
          this.frameIndex = 0;
        }
      }
    };
    render = () => {
      // Clear the canvas
      this.context.clearRect(0, 0, this.width, this.height);
			this.context.scale(-1, 1);
this.context.drawImage(this.image, -this.image.width, 0);

      // Draw the animation
      this.context.drawImage(
        this.image,
        (this.frameIndex * this.width) / this.numberOfFrames,
        0,
        this.width / this.numberOfFrames,
        this.height,
        0,
        0,
        this.width / this.numberOfFrames,
        this.height
      );
						// this.context.scale(-1, 1);

    };
  }

  // Get canvas
  canvas = document.getElementById("hedgehog");
  canvas.width = 269;
  canvas.height = 351;

  // Create sprite sheet
  hedgehogImage = new Image();

  // Create sprite
  hedgehog = new sprite({
    context: canvas.getContext("2d"),
    width: 1615,
    height: 351,
    image: hedgehogImage,
    numberOfFrames: 6,
    ticksPerFrame: 10
  });

  function gameLoop() {
    window.requestAnimationFrame(gameLoop);

    hedgehog.update();
    hedgehog.render();
		hedgehog.context.scale(-1, 1)
  }

  // Load sprite sheet
  hedgehogImage.addEventListener("load", gameLoop);
  hedgehogImage.src = "https://i.imgur.com/JKPX5Zs.png";
})();

How to flip an image with the HTML5 canvas without scaling

Flipping things horizontally or vertically

Sprite Animation

https://stackoverflow.com/questions/23378123/flip-sprite-horizontally-or-render-new-sprite-on-right-left-key-down


上一篇
Day 08 - JS 型別守護者 TypeScript
下一篇
Day 10 - RXJS 事件流
系列文
以前端角度探討遊戲化的資訊設計13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言