html人物移动,使用canvas完成人物的移动

绘制图片

canvas{

border:1px solid pink;

display:block;

margin:100px auto;

}

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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值