Skip to main content

HTML5 canvas 精灵教程

要使用 Konva 创建一个动画精灵,我们可以实例化一个 Konva.Sprite() 对象。

完整的属性和方法列表,请查看 精灵 API 参考

import Konva from 'konva';

const stage = new Konva.Stage({
  container: 'container',
  width: window.innerWidth,
  height: window.innerHeight
});

const layer = new Konva.Layer();
stage.add(layer);

const animations = {
  idle: [
    2, 2, 70, 119,      // 帧 1
    71, 2, 74, 119,     // 帧 2
    146, 2, 81, 119,    // 帧 3
    226, 2, 76, 119,    // 帧 4
  ],
  punch: [
    2, 138, 74, 122,    // 帧 1
    76, 138, 84, 122,   // 帧 2
    346, 138, 120, 122, // 帧 3
  ],
};

const imageObj = new Image();
imageObj.onload = function() {
  const sprite = new Konva.Sprite({
    x: 50,
    y: 50,
    image: imageObj,
    animation: 'idle',
    animations: animations,
    frameRate: 7,
    frameIndex: 0
  });

  layer.add(sprite);
  sprite.start();

  // 添加击打按钮功能
  const button = document.createElement('button');
  button.textContent = '击打';
  button.style.position = 'absolute';
  button.style.top = '0';
  button.style.left = '0';
  document.body.appendChild(button);

  button.addEventListener('click', () => {
    sprite.animation('punch');
    sprite.on('frameIndexChange.button', function() {
      if (this.frameIndex() === 2) {
        setTimeout(() => {
          sprite.animation('idle');
          sprite.off('.button');
        }, 1000 / sprite.frameRate());
      }
    });
  });
};
imageObj.src = 'https://konvajs.org/assets/blob-sprite.png';