<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>绘制图片</title>
<style type="text/css">
canvas{
border:1px solid pink;
display:block;
margin:100px auto;
}
</style>
</head>
<body>
<canvas width="600px" height="400px">
</canvas>
<script type="text/javascript">
var myCanvas =document.querySelector("canvas");
var ctx =myCanvas.getContext("2d");
var speed =5;//每次移动的速度
var img =new Image();//创建image对象
img.src ="../image/demo01/04.png";
var imageWidth =img.width;//图片的宽
var imageHeight =img.height;//图片的高
var peopleWidth=imageWidth/4;//人物的宽
var peopleHeight =imageHeight/4;//人物的高
var rowIndex =0;//行
var colIndex =0;//列
var x =300;//默认的起始位置
var y =200;//默认的起始位置
img.onload =function(){
ctx.drawImage(img,colIndex*peopleWidth,rowIndex*peopleHeight,peopleWidth,peopleHeight,x ,y ,peopleWidth,peopleHeight);
//从键盘上获取相应的值
document.onkeydown =function(e){
console.log(e.keyCode);
switch (e.keyCode){
case 38:
rowIndex =3;
y =y -speed;
break;
case 39:
rowIndex =2;
x =x +speed;
break;
case 40:
rowIndex =0;
y =y +speed;
break;
case 37:
rowIndex =1;
x =x -speed;
break;
}
colIndex++;
if(colIndex ==4){
colIndex =0;
}
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.drawImage(img,colIndex*peopleWidth,rowIndex*peopleHeight,peopleWidth,peopleHeight,x ,y ,peopleWidth,peopleHeight);
}
}
</script>
</body>
</html>