<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>img</title>
</head>
<body>
<div id="container">
<canvas id="canvas"></canvas>
</div>
<h2>点击改变方向</h2>
<button id="btn-left">左</button>
<button id="btn-right">右</button>
<button id="btn-top">前</button>
<button id="btn-down">后</button>
<script type="text/javascript">
(function(){
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
canvas.width=600;
canvas.height=600;
canvas.style.border="1px solid #000";
//开始绘图
var img=new Image();
var dirIndex=0;
img.src='img/boy.png';
img.οnlοad=function(){
var i=0;
setInterval(function(){
// ctx.clearRect(0,0,canvas.width,canvas.height);//清除之前的图片
canvas.width=canvas.width;//这个方法会清除全部
ctx.drawImage(
img
,40*i//截取x坐标
,dirIndex*65//截取y坐标
,40//截取w
,65//截取h
,200
,200
,80
,130
);
i++;
if(i>=4){
i=0;
}
},300)
// ctx.drawImage(img,100,100);
};
//绑定按钮的点击事件
var btnLeft=document.getElementById('btn-left');
btnLeft.οnclick=function(){
dirIndex=1;
}
var btnRight=document.getElementById('btn-right');
btnRight.οnclick=function(){
dirIndex=2;
}
var btnTop=document.getElementById('btn-top');
btnTop.οnclick=function(){
dirIndex=0;
}
var btnDown=document.getElementById('btn-down');
btnDown.οnclick=function(){
dirIndex=3;
}
}());
</script>
</body>
</html>