Sprite Animator
Animation module for sprites
by hyperthalamus
HTML
<div id="playerArea"></div>
<button id="start">start</button><button id="stop">stop</button>
CSS
#playerArea {
position: relative;
background: #ccc;
width: 640px;
height: 360px;
}
JavaScript
function SpriteAnimator(config) {
var parent = $(config.parentSelector),
el,
index = 0,
position,
update,
api = {};
el = $('<div></div>')
.appendTo(parent)
.css({
"position": "absolute",
"top": (parent.height() - config.height) / 2,
"left": (parent.width() - config.width) / 2,
"width": config.width,
"height": config.height,
"background-image": "url(" + config.sprite + ")",
"display":"none"
});
api.start = function () {
clearInterval(update);
update = setInterval(function() {
index = (index < config.frames)? index + 1 : 0;
position = (-config.width * index) + "px";
el.css("background-position", position + " 0");
}, config.framespeed);
el.css("display", "block");
}
api.stop = function () {
clearInterval(update);
el.css("display", "none");
}
return api;
}
function init() {
var loader = SpriteAnimator({
parentSelector: "#playerArea",
frames: 16,
width: 128,
height: 128,
framespeed: 50,
sprite: "http://herbalife.mercularity.com/img/player_loading_sprite.png"
});
loader.start();
$("#start").click(function() { loader.start(); });
$("#stop").click(function() { loader.stop(); });
}
$(init);