<canvas width="600px" height="400px"></canvas>
<script>
var myCanvas = document.querySelector("canvas");
var ctx = myCanvas.getContext("2d");
var Person=function(ctx){
this.ctx=ctx || document.querySelector("canvas").getContext("2d");
this.src="image/04.png";
this.canvasHeight=this.ctx.canvas.height;
this.canvasWidth=this.ctx.canvas.width;
//行走相关参数
this.stepSize=10;
//0前 1左 2右 3后
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);
console.log("hhh1");
};
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,
//用index确定图片的x
//用direction确定图片的y
this.x0+this.stepX*this.stepSize,this.y0+this.stepY*this.stepSize,
this.personWidth,this.personHeight
);
if(this.index>=3){
this.index=0;
}
};
new Person();
</script>
canvas 人物根据按键移动动画案例
最新推荐文章于 2023-12-11 10:30:26 发布