与键盘进行交互

通过onkeydown获取键盘事件

onkeydown 的事件对象 event

event.keyCode/event.which 得到的是一个按键对应的数字值(Unicode 编码)

常用键值对应如下:

数字值 实际键值
48到57 0到9
65到90 a到z(A到Z)
112到135 F1到F24
8 BackSpace(退格)
9 Tab
13 Enter(回车)
20 Caps_Lock(大写锁定)
32 Space(空格键)
37 Left(左箭头)
38 Up(上箭头)
39 Right(右箭头)
40 Down(下箭头)

键盘操作案例

说明:

  • 通过 上/下/左/右 控制小点的移动
  • 小点碰撞到墙壁会从相对的方向出现
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <title>test</title>
  <style>
    canvas {
      border: 6px double black;
      background: white;
    }
  </style>
</head>
<body>
  <canvas id="canvas"></canvas>
  <script>
    var canvas = document.querySelector('#canvas')
    var context = canvas.getContext('2d')
    var curPoint = {
      x: 0,
      y: 0,
      w: 10,
      h: 10
    }
    context.fillRect(curPoint.x, curPoint.y, curPoint.w, curPoint.h);
    // 当用户按下键盘上的键时的处理函数
    window.onkeydown = function (e) {
      var dx, dy
      if (e.keyCode == 38) {
        // 按下了向上键,向上移动
        dy = -curPoint.h;
      } else if (e.keyCode == 40) {
        // 按下了向下键,向下移动
        dy = curPoint.h;
      } else if (e.keyCode == 37) {
        // 按下了向左键,向左移动
        dx = -curPoint.w;
      } else if (e.keyCode == 39) {
        // 按下了向右键,向右移动
        dx = curPoint.w;
      } else {
        return
      }
      context.save();
      context.fillStyle = '#fff';
      context.fillRect(0, 0, canvas.width, canvas.height);
      context.restore();
      if (dx) {
        curPoint.x += dx
        if (curPoint.x >= canvas.width) {
          curPoint.x = 0
        } else if (curPoint.x < 0) {
          curPoint.x = canvas.width - curPoint.w
        }
      }
      if (dy) {
        curPoint.y += dy
        if (curPoint.y >= canvas.height) {
          curPoint.y = 0
        } else if (curPoint.y < 0) {
          curPoint.y = canvas.height - curPoint.h
        }
      }
      context.fillRect(curPoint.x, curPoint.y, curPoint.w, curPoint.h);
    }
  </script>
</body>
</html>

MIT Licensed | Copyright © 2018-present 滇ICP备16006294号

Design by Quanzaiyu | Power by VuePress