HTML5 canvas Sprite Tutorial

获取Konva最新的信息

我们可以通过实例化一个 Konva.Sprite() 对象创建精灵图。

点击 Konva.Sprite documentation 查看详细属性和方法说明。

Konva Sprite Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/konva@4.0.18/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Sprite Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
#punch {
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div id="container"></div>
<button id="punch">Punch</button>
<script>
var width = window.innerWidth;
var height = window.innerHeight;

var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});

var layer = new Konva.Layer();
var animations = {
idle: [
// x, y, width, height (4 frames)
2, 2, 70, 119,
71, 2, 74, 119,
146, 2, 81, 119,
226, 2, 76, 119
],
punch: [
// x, y, width, height (4 frames)
2, 138, 74, 122,
76, 138, 84, 122,
346, 138, 120, 122
]
};

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

// add the shape to the layer
layer.add(blob);

// add the layer to the stage
stage.add(layer);

// start sprite animation
blob.start();

// resume transition
document.getElementById('punch').addEventListener(
'click',
function() {
blob.animation('punch');
blob.on('frameIndexChange.button', function() {
if (this.frameIndex() === 2) {
setTimeout(function() {
blob.animation('idle');
blob.off('.button');
}, 1000 / blob.frameRate());
}
});
},
false
);
};
imageObj.src = '/assets/blob-sprite.png';
</script>
</body>
</html>