<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>03-实现baby案例</title> <style> canvas { border: 1px solid #000; } </style> </head> <body> <canvas id="canvas" width="600" height="400"></canvas> <!--<script src="./My-solider.js"></script>--> <script> function Solider(options){ /*属性*/ this.width=options.width||40; this.height=options.height||65; this.frame=options.frame||0; this.direction=options.direction||0; this.imgSrc=options.imgSrc; this.image=new Image(); this.x=options.x||0; this.y=options.y||0; this.step=options.step||1; this.context=options.context; /*定时器*/ this.timer=null; /*判断是否在走ing*/ this.isWalking=false; /*初始化*/ this.init(); } /*方法*/ Solider.prototype={ constructor:Solider, /*初始化动画*/ init:function(){ var that=this; /*图片加载完成后,绑定事件并绘制一次图片*/ this.image.addEventListener('load',function(){ that.bind(); that.draw(); }) /*初始化动画*/ this.image.src=this.imgSrc; }, /*更新状态*/ update:function(){ /*获取canvas的宽和高*/ var w=this.context.canvas.width, h=this.context.canvas.height; /*1 更新帧*/ this.frame= ++this.frame%4; /*更新人物位置*/ switch (this.direction){ case 0://down this.y+=this.step; if(this.y>=h){ this.y=-this.height-10; } break; case 1://left this.x-=this.step; if(this.x<=-this.width){ this.x=w+10; } break; case 2://right this.x+=this.step; if(this.x>=w){ this.x=-this.width-10; } break; case 3://up this.y-=this.step; if(this.y<=-this.height){ this.y=h+10; } break; } }, /*开始动画*/ start:function(){ var that=this; this.isWalking=true; this.timer=setInterval(function(){ that.update(); that.draw(); },80) }, /*停止动画*/ stop:function(){ this.isWalking=false; window.clearInterval(this.timer); }, /*事件绑定*/ bind:function(){ var that=this; window.document.addEventListener('keydown',function(e){ /*获取keycode*/ var keycode= e.keyCode; console.log(keycode); /*判断是否按下空格键*/ if(keycode==32){ /*判断当前是否在运动*/ if(that.isWalking){ that.stop(); }else{ that.start(); } } /*如果动画已经停止了,那么下面的代码不需要执行*/ if(!that.isWalking){ return; } /*如果正在执行动画,去监听键盘。改变方向*/ switch (keycode){ case 38: case 87: //up that.direction=3; break; case 39: case 68: //right that.direction=2; break; case 40: case 83: //down that.direction=0; break; case 37: case 65: //left that.direction=1; break; } }) }, /*根据状态绘制动画*/ draw:function(){ var context=this.context; var w=context.canvas.width, h=context.canvas.height; /*1 清除画布*/ context.clearRect(0,0,w,h); /*绘制小人图片*/ context.drawImage(this.image,this.frame*this.width,this.direction*this.height,this.width,this.height, this.x,this.y,this.width,this.height); } } /*测试*/ new Solider({ imgSrc:'http://cdn.attach.qdfuns.com/notes/pics/201705/23/230433jwz0t1ee201amut9.png', context:document.getElementById('canvas').getContext('2d'), step:5 }) </script> </body> </html>
欢迎分享本文,转载请保留出处:前端ABC » canvas人物动作,按空格键开始