<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Canvas</title>
<style type="text/css">
*{margin: 0;padding: 0;}
html{overflow: hidden;}
#box{
background: #242424;
}
</style>
</head>
<body>
<!--<canvas width="800px" height="800px">你的不兼容</canvas> 不兼容时会显示出文本内容-->
<canvas id="box"></canvas>
</body>
<script src="js/canvas.js"></script>
</html>
(function(){
var rectX = 0;
var rectY = 0;
var timer=null;
function init(){
var canvasELe=document.getElementById('box');
//设置全屏
canvasELe.width = innerWidth;
canvasELe.height = innerHeight;
//获得画布上下文:CanvasRenderinginfo.conteinfo.xt2D
var context=canvasELe.getContext('2d');
rectX=50;
rectY=50;
drawReact({
context:context,
strokeColor:'red',
linewidth:3,
fillColor:'white',
x:rectX,
y:rectY,
width:50,
height:50
});
//传入一个数组对象
function drawReact(info){
if(!info){
alert('必须传参数');
return;
};
//重新开始一个路径
info.context.beginPath();
info.context.lineWidth = info.linewidth;
info.context.strokeStyle=info.strokeColor;
info.context.fillStyle=info.fillColor;
info.context.moveTo(info.x,info.y);
info.context.lineTo(info.x+info.width,info.y);
info.context.lineTo(info.x+info.width,info.y+info.height);
info.context.lineTo(info.x,info.y+info.height);
info.context.closePath();
info.context.fill();
info.context.stroke();
};
//三秒后清除屏幕
/*setTimeout(function(){
context.clearRect(0,0,innerWidth,innerHeight);
},3000);*/
function rectControl(context){
//监听键盘按下
document.onkeydown=function(event){
//console.log(event);
var dis='';
switch(event.keyCode){
//w
case 87:
case 38:
dis='top';
break;
//a
case 65:
case 37:
dis='left';
break;
//s
case 83:
case 40:
dis='bottom';
break;
//d
case 68:
case 39:
dis='right';
break;
default:
break;
};
move(context,dis);
};
document.onkeyup=function(direction){
clearInterval(timer);
timer=null;
}
}
function move(context,direction){
//清除上一帧的内容
context.clearRect(0,0,innerWidth,innerHeight);
//定义一个移动变量
var distance=1;
switch(direction){
case 'left':
rectX-=distance;
break;
case 'right':
rectX+=distance;
break;
case 'top':
rectY-=distance;
break;
case 'bottom':
rectY+=distance;
break;
}
drawReact({
context:context,
strokeColor:'red',
linewidth:3,
fillColor:'white',
x:rectX,
y:rectY,
width:50,
height:50
});
if(timer){return;}
timer=setInterval(function(){
move(context,direction);
},10);
}
rectControl(context);
};
init();
})();
效果图:
按W S A D健 或者 上 下 左 右健可移动