使用canvas完成人物的移动

<!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>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容