素材img
代码
var Person = function (ctx) {
this.ctx = ctx || document.querySelector('canvas').getContext('2d');
this.src = 'image/04.png';
this.canvasWidth = this.ctx.canvas.width;
this.canvasHeight = this.ctx.canvas.height;
this.stepSzie = 10;
this.direction = 0;
this.stepX = 0;
this.stepY = 0;
this.init();
};
Person.prototype.init = function () {
var that = this;
this.loadImage(function (image) {
that.imageWidth = image.width;
that.imageHeight = image.height;
that.personWidth = that.imageWidth / 4;
that.personHeight = that.imageHeight / 4;
that.x0 = that.canvasWidth / 2 - that.personWidth / 2;
that.y0 = that.canvasHeight / 2 - that.personHeight / 2;
that.ctx.drawImage(image,
0,0,
that.personWidth,that.personHeight,
that.x0,that.y0,
that.personWidth,that.personHeight);
that.index = 0;
document.onkeydown = function (e) {
if(e.keyCode == 40){
that.direction = 0;
that.stepY ++;
that.drawImage(image);
}else if(e.keyCode == 37){
that.direction = 1;
that.stepX --;
that.drawImage(image);
}else if(e.keyCode == 39){
that.direction = 2;
that.stepX ++;
that.drawImage(image);
}else if(e.keyCode == 38){
that.direction = 3;
that.stepY --;
that.drawImage(image);
}
}
});
}
Person.prototype.loadImage = function (callback) {
var image = new Image();
image.onload = function () {
callback && callback(image);
};
image.src = this.src;
};
Person.prototype.drawImage = function (image) {
this.index ++;
this.ctx.clearRect(0,0,this.canvasWidth,this.canvasHeight);
this.ctx.drawImage(image,
this.index * this.personWidth,this.direction * this.personHeight,
this.personWidth,this.personHeight,
this.x0 + this.stepX * this.stepSzie ,this.y0 + this.stepY * this.stepSzie,
this.personWidth,this.personHeight);
if(this.index >= 3){
this.index = 0;
}
};
new Person();
效果图