mirror of
https://github.com/konvajs/konva.git
synced 2025-09-23 04:36:47 +08:00
added new Kinetic.Sprite shape that enables you to easily add animated sprites to the stage
This commit is contained in:
91
src/shapes/Sprite.js
Normal file
91
src/shapes/Sprite.js
Normal file
@@ -0,0 +1,91 @@
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
// Sprite
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
/**
|
||||
* Sprite constructor
|
||||
* @constructor
|
||||
* @augments Kinetic.Shape
|
||||
* @param {Object} config
|
||||
*/
|
||||
Kinetic.Sprite = function(config) {
|
||||
this.setDefaultAttrs({
|
||||
index: 0,
|
||||
frameRate: 17
|
||||
});
|
||||
|
||||
config.drawFunc = function() {
|
||||
if(this.image !== undefined) {
|
||||
var context = this.getContext();
|
||||
var anim = this.attrs.animation;
|
||||
var index = this.attrs.index;
|
||||
var f = this.attrs.animations[anim][index];
|
||||
|
||||
context.beginPath();
|
||||
context.rect(0, 0, f.width, f.height);
|
||||
context.closePath();
|
||||
context.drawImage(this.image, f.x, f.y, f.width, f.height, 0, 0, f.width, f.height);
|
||||
}
|
||||
};
|
||||
// call super constructor
|
||||
Kinetic.Shape.apply(this, [config]);
|
||||
};
|
||||
/*
|
||||
* Sprite methods
|
||||
*/
|
||||
Kinetic.Sprite.prototype = {
|
||||
/**
|
||||
* start sprite animation
|
||||
*/
|
||||
start: function() {
|
||||
var that = this;
|
||||
var layer = this.getLayer();
|
||||
this.interval = setInterval(function() {
|
||||
that._updateIndex();
|
||||
layer.draw();
|
||||
if(that.afterFrameFunc && that.attrs.index === that.afterFrameIndex) {
|
||||
that.afterFrameFunc();
|
||||
}
|
||||
}, 1000 / this.attrs.frameRate)
|
||||
},
|
||||
/**
|
||||
* stop sprite animation
|
||||
*/
|
||||
stop: function() {
|
||||
clearInterval(this.interval);
|
||||
},
|
||||
/**
|
||||
* set after frame event handler
|
||||
* @param {Integer} index frame index
|
||||
* @param {Function} func function to be executed after frame has been drawn
|
||||
*/
|
||||
afterFrame: function(index, func) {
|
||||
this.afterFrameIndex = index;
|
||||
this.afterFrameFunc = func;
|
||||
},
|
||||
/**
|
||||
* set animation key
|
||||
* @param {String} anim animation key
|
||||
*/
|
||||
setAnimation: function(anim) {
|
||||
this.attrs.animation = anim;
|
||||
},
|
||||
/**
|
||||
* set animation frame index
|
||||
* @param {Integer} index frame index
|
||||
*/
|
||||
setIndex: function(index) {
|
||||
this.attrs.index = index;
|
||||
},
|
||||
_updateIndex: function() {
|
||||
var i = this.attrs.index;
|
||||
var a = this.attrs.animation;
|
||||
if(i < this.attrs.animations[a].length - 1) {
|
||||
this.attrs.index++;
|
||||
}
|
||||
else {
|
||||
this.attrs.index = 0;
|
||||
}
|
||||
}
|
||||
};
|
||||
// extend Shape
|
||||
Kinetic.GlobalObject.extend(Kinetic.Sprite, Kinetic.Shape);
|
Reference in New Issue
Block a user