如图所示,小人在一直走动,并且点击上下左右时,会改变人走动的方向
源图片:
源代码:
html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>面向对象</title>
<script src="js/zxj.js" type="text/javascript"></script>
</head>
<body>
<div id="container">
<canvas id="cavsElem">
你的浏览器不支持canvas
</canvas>
</div>
<button id="btn-dir-left">←</button>
<button id="btn-dir-right">→</button>
<button id="btn-dir-up">↑</button>
<button id="btn-dir-down">↓</button>
<script type="text/javascript">
(function(){
var canvas=document.getElementById('cavsElem');
// var ctx=canvas.getContext('2d');
var ctx=canvas.getContext('2d');
canvas.width=600;
canvas.height=600;
canvas.style.border="1px solid #000";
var s = new Sprite({
x: 200,
y: 200,
w: 40*4,
h: 65*4,
speed: 4,
w0: 40,
h0: 65,
imgSrc: 'imgs/gameImgs/DMMban.png'
});
//渲染 动画
s.render(ctx);
var buttons=document.getElementsByTagName('button');
buttons[0].οnclick=function(){
s.changeDirection('left');
}
buttons[1].οnclick=function(){
s.changeDirection('right');
}
buttons[2].οnclick=function(){
s.changeDirection('up');
}
buttons[3].οnclick=function(){
s.changeDirection('down');
}
}());
</script>
</body>
</html>
javascript代码如下:js.js
//封装对象
// 属性:width,height,
// 行为:render,changeDirection
function Sprite(option){
this._init(option);
}
Sprite.prototype={
_init:function(option){
this.imgSrc=option.imgSrc;
this.x=option.x===0?0:option.x;
this.y=option.y===0?0:option.y;
//canvas上显示的款宽度和高度
this.w=option.w||40;
this.h=option.h||65;
//裁剪后的宽高
this.w0=option.w0||40;
this.h0=option.h0||65;
this.dirIndex=0;
this.speed=option.speed||10;
},
//画图
render:function(ctx){
var img=new Image();
img.src=this.imgSrc;
var that=this;
img.οnlοad=function(){
var i=0;
setInterval(function(){
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);//ctx就是传递过来的上下文
// ctx.canvas.width=ctx.canvas.width;
ctx.drawImage(
img,
that.w0*i,
that.h0*that.dirIndex,
that.w0,
that.h0,
that.x,
that.y,
that.w,
that.h
);
i++;
i=i%4;
},1000/that.speed);
}
},
changeDirection:function(dir){
if(dir=='left'){
this.dirIndex=1;
}else if(dir=='right'){
this.dirIndex=2;
}
else if(dir=='up'){
this.dirIndex=3;
}else{
this.dirIndex=0;
}
}
};