<!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.οnkeydοwn=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.οnkeyup=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健 或者 上 下 左 右健可移動