console
var image = new Image();
image.src = 'http://06wjin.sinaapp.com/html5/billd/img/billd-stand.png';
var sprite = function(opt) {
var sprite_proto = {};
sprite_proto.image = opt.image;
sprite_proto.rect = opt.rect;
sprite_proto.frames = opt.frames;
sprite_proto.fps = opt.fps || 1;
sprite_proto.current_frame_idx = 0;
sprite_proto.next = function() {
var cur_frame = this.frames[this.current_frame_idx];
this.current_frame_idx += 1;
if (this.current_frame_idx == this.frames.length) {
this.current_frame_idx = 0;
}
return cur_frame;
};
return sprite_proto;
}
var butterfly = sprite({
image: image,
rect:{x: 0, y: 0, w: 120, h: 120},
frames: [
{x: 0, y: 0, w: 120, h: 120},
{x: 120, y: 0, w: 120, h: 120},
{x: 240, y: 0, w: 120, h: 120},
{x: 360, y: 0, w: 120, h: 120},
{x: 480, y: 0, w: 120, h: 120},
{x: 600, y: 0, w: 120, h: 120}
]
});
var canvas = document.getElementById('butterfly');
canvas.width = 120;
canvas.height = 120;
var world = function(opt) {
var world_proto = {};
world_proto.context = opt.context;
world_proto.rect = opt.rect;
world_proto.clear = function() {
this.context.clearRect(0, 0, this.rect.w, this.rect.h);
}
world_proto.render = function(sprite) {
var frame = sprite.next();
this.context.drawImage(
sprite.image,
frame.x,
frame.y,
frame.w,
frame.h,
0,
0,
sprite.rect.w,
sprite.rect.h
);
}
return world_proto;
}
var my_world = world({
context: canvas.getContext('2d'),
rect: {x: 0, y: 0, w: 600, h: 120},
fps: 30,
});
image.addEventListener('load', function(){
setInterval(function(){
my_world.clear();
my_world.render(butterfly);
},20);
});
<canvas id="butterfly"></canvas>