跳到主要内容

HTML5 Canvas 精灵教程

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

有关完整的属性和方法列表,请参阅 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, // frame 1
71, 2, 74, 119, // frame 2
146, 2, 81, 119, // frame 3
226, 2, 76, 119, // frame 4
],
punch: [
2, 138, 74, 122, // frame 1
76, 138, 84, 122, // frame 2
346, 138, 120, 122, // frame 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();

// Add punch button functionality
const button = document.createElement('button');
button.textContent = 'Punch';
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';