HTML5初学---坦克大战基础
让小球动起来,根据键盘的W(上),D(右),S(下),A(左);键的点击移动小球
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> </head> <body onkeydown="test()"> <h1>html5-经典的坦克大战</h1> <canvas id="tankeMap" width="500px" height="500px" style="background-color:black"> </canvas> <script type="text/javascript"> //准备工作 //得到画布 var canvas1=document.getElementById("tankeMap"); //得到上下文引用对象,你可以理解成画笔 var cxt=canvas1.getContext("2d"); var ballX=30; var ballY=30; //画中间的圆形的炮筒体 //画圆时必须要把beginPath和closePath加上 function drawball(){ cxt.fillStyle="#FF0000"; cxt.beginPath();//重要,必须加上 cxt.arc(ballX,ballY,15,0,360,false); cxt.closePath();//重要,必须加上 cxt.fill(); } drawball(); function test(){ var code=event.keyCode; cxt.clearRect(0,0,500,500); switch(code){ case 87: ballY--; break; case 68: ballX++; break; case 83: ballY++; break; case 65: ballX--; break; } drawball(); } </script> </body> </html>