首页 > 代码库 > Html5 小球键盘移动

Html5 小球键盘移动

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>    <title></title></head><body onkeydown="test()">    <h1>小球上下移动</h1>    <canvas id="test" width="400px" height="300px" style="background-color: black"></canvas>    <script type="text/javascript">        //得到画布        var canvas1 = document.getElementById("test");        //取得画布画笔对象        var cxt = canvas1.getContext("2d");        //画出红色圆球        cxt.beginPath();        cxt.fillStyle = "#FF0000";        cxt.arc(30, 30, 10, 0, 360, true);        cxt.closePath();        cxt.fill();        //键盘发生事件 让小球移动 w d s a        //按下一个键,实际上触发一个onkeydow事件        var ballX = 30;        var bally = 30;        function test() {            cxt.clearRect(0,0,400,300);            var code = event.keyCode;            switch (code) {                case 87:                    bally--;                    break;                case 68:                    ballX++;                    break;                case 83:                    bally++;                    break;                case 65:                    ballX--;                    break;            }            drawBall();        }        //重新绘制        function drawBall() {            cxt.beginPath();            cxt.fillStyle = "#FF0000";            cxt.arc(ballX, bally, 10, 0, 360, true);            cxt.closePath();            cxt.fill();        }    </script></body></html>