我正在尝试通过键盘移动画布元素

时间:2019-11-02 10:58:03

标签: javascript html html5-canvas

我知道这个问题已经被像q2i3648123648那样回答了,但是由于某种原因,我试图使红色方块随键盘移动,但是该代码适用于鼠标事件,但似乎不适用于键盘输入 这是javascript代码

let canvas;
let canvasContext;

let playerPositionX = 10;
let playerPositionY = 10;
let playerSpeed = 5;
const load = () => {
  canvas = document.getElementById("gameCanvas");
  canvasContext = canvas.getContext('2d');


  let framesPerSecond = 30;
  setInterval(() => {
    gameObjects();
  }, 1000 / framesPerSecond);
  // moving the player
  canvas.addEventListener("onkeydown", (e) => {
      if(e.keyCode === 87){
        playerPositionX += playerSpeed;
      }
  });

};
const gameObjects = () => {
  // canvas
  component(0, 0, canvas.width, canvas.height, 'black');

  // player
  component(playerPositionX, playerPositionY, 30, 30, 'red');
};

const component = (positionX, positionY, width, height, color) => {
  canvasContext.fillStyle = color;
  canvasContext.fillRect(positionX, positionY, width, height);
};



window.onload = load;

1 个答案:

答案 0 :(得分:1)

KeyboardEvent.keyCode是已折旧的属性。使用KeyboardEvent.code

  • 将键盘事件监听器与控制逻辑分开。
  • 收听按键按下和按键按下事件,并设置特定按键按下的标志。
  • 在主循环中检查该标志并根据需要进行移动。
  • 使用server { server_name d1.example.com; location / { proxy_pass http://127.0.0.1:8081; } } server { server_name d2.example.com; location / { proxy_pass http://127.0.0.1:8082; } } 进行渲染。

示例

以下示例显示了如何创建键盘界面。它消除了键盘自动重复的麻烦。您可以根据需要通过仅设置[requestAnimationFrame][3]

来停止输入

keys.nameOfKey = false;
const ctx = canvas.getContext("2d");
const frameRate = 30;  // must divide into 60 by whole number eg 60,30,20,15,10
var frameCount = 0;

// define keys to listen to
const keys = {
    ArrowUp: false,
    ArrowDown: false,
    ArrowLeft: false,
    ArrowRight: false,
    anykey: false,
};

// sets key to true if key is down
function keyboardEvent(event) {
    if (keys[event.code] !== undefined) {
         keys[event.code] = event.type === "keydown";
         event.preventDefault();
         event.type === "keydown" && (keys.anykey = true);
    }
}

// add key listeners to window
addEventListener("keydown", keyboardEvent);
addEventListener("keyup", keyboardEvent);

// For SO snippet as it will not focus without user click.
canvas.addEventListener("click",() =>  requestAnimationFrame(update), {once: true});
ctx.font = "16px arial";
ctx.textAlign = "center";
ctx.fillText("Click to focus keyboard", canvas.width / 2, canvas.height / 2);


const player = {
    x: 0, y: 0, w: 10, h: 10, speed: 5,
    draw() {
        ctx.fillRect(player.x, player.y, player.w, player.h);
    },
    move() {
        if (keys.ArrowUp) { player.y -= player.speed }
        if (keys.ArrowDown) { player.y += player.speed }
        if (keys.ArrowRight) { player.x += player.speed }
        if (keys.ArrowLeft) { player.x -= player.speed }
        if (player.y < 0) { player.y = 0 }
        if (player.y + player.h > canvas.height ) { player.y = canvas.height - player.h }
        if (player.x + player.w > canvas.width ) { player.x = canvas.width - player.w }
        if (player.x < 0) { player.x = 0 }
    }
}

function update(){
     if (frameCount % (60 / frameRate) === 0) {
         ctx.clearRect(0,0,canvas.width, canvas.height);
         player.move();
         player.draw();
         if (!keys.anykey) {
             ctx.fillText("Arrow keys to move!", canvas.width / 2, canvas.height / 2);
         }
     }
     frameCount += 1;
     requestAnimationFrame(update);
}
canvas {
    border: 2px solid black;
}