使用键代码移动画布-JAVASCRIPT

Move a canvas with keycode - JAVASCRIPT

本文关键字:动画 -JAVASCRIPT 移动 代码      更新时间:2023-09-26

我对javascript很陌生。在谷歌的帮助下,我写了这篇文章。我不知道为什么,但当我按下"A"或"D"键时,什么都不会发生。我只是不明白为什么,对我来说,这一切都是完美的感觉。你能帮我吗?

canvas = document.getElementById("canvas");
ctx = canvas.getContext('2d');
var X = 50;
var Y = 50;
var WIDTH = 35;
var HEIGHT = 35;
ctx.fillStyle = "#FF0000";
ctx.fillRect(X,Y,WIDTH,HEIGHT);
document.addEventListener("keydown", draw);
function draw(e){
    switch(e.which || e.keyCode){
        case 68:
            x += 5;
            break;
        case 65:
            x -= 5;
            break;
  }
  ctx.clear();
  ctx.fillStyle = "#FF0000";
  ctx.fillRect(X,Y,WIDTH,HEIGHT);
}

和HTML:

<canvas id="canvas" width="350px" height="500px"></canvas>

如果有用的话,这里有一把小提琴。https://jsfiddle.net/Scrubben/gmd537k1/26/

这是工作代码。请确保JavaScript区分大小写。所以var X !== x。并使用ctx.clearRect(0, 0, canvas.width, canvas.height);而不是ctx.clear()

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
var x = 50;
var y = 50;
var WIDTH = 35;
var HEIGHT = 35;
ctx.fillStyle = "#FF0000";
ctx.fillRect(x, y, WIDTH, HEIGHT);
document.addEventListener("keydown", draw);
function draw(e) {
  switch (e.which || e.keyCode) {
    case 68:
      x += 5;
      break;
    case 65:
      x -= 5;
      break;
  }
  // ctx.clear();
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#FF0000";
  ctx.fillRect(x, y, WIDTH, HEIGHT);
}
#canvas {
  border: 2px solid black;
}
<canvas id="canvas" width="500px" height="500px"></canvas>