键盘事件(上下左右)

<style>

    #canvas {

        position: absolute;

        left: 50%;

        top: 50%;

        /* width: 500px;

        height: 500px; */

        transform: translate(-50%, -50%);

        border: 2px black solid;

    }

</style>

<body>

<canvas width="500px" height="500px" id="canvas">您的浏览器版本过低</canvas>

 <script>

        var canvas = document.getElementById('canvas');

        var c = canvas.getContext('2d');

        var w = 500;

        var h = 500;

        var x = 100;

        var y = 100;

        var r = 20;

        // 水平速度

        xSpeed = 5;

        // 垂直速度

        ySpeed = 5;

        setInterval(function () {

            c.clearRect(0, 0, w, h);

            move();

            // 更新圆的位置

            drawCircle(x, y, r);

        }, 10)

function move () {

            document.onkeydown = function (event) {

                if (event.keyCode === 38) {

                    console.log("上键被按下了");

                                 //以下三种都可以实现上移键盘事件

                  y = y - ySpeed;

                    // setInterval(function () { y = y - ySpeed; }, 10)

                    // y--

            

                } else if (event.keyCode === 40) {

                    console.log("下键被按下了");

                              //以下三种都可以实现下移键盘事件

                    // setInterval(function () { y = y + ySpeed; }, 10)

                    y = y + ySpeed;

                    // y++;

                    

                } else if (event.keyCode === 37) {

                    console.log("左键被按下了");

                  //以下三种都可以实现左移键盘事件

                    // setInterval(function () { x = x - xSpeed; }, 10)

                    // xSpeed = xSpeed;

                    x = x - xSpeed;

                    // x--;

                  

                } else if (event.keyCode === 39) {

                    console.log("右键被按下了");

                    // setInterval(function () { x = x + xSpeed; }, 10)

                    // return ;

                    // exit(0);

                    x = x + xSpeed;

                    // x++;

                }

            };

        }

//画圆

  function drawCircle (x, y, r) {

            c.beginPath();

            c.arc(x, y, r, 0, Math.PI * 2);

            c.fillStyle = 'gold';

            c.fill();

}

    </script>

</body>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值