无法在 canvas 移动时生成正方形,现在正方形也不会绘制

Can't make square on canvas move, and now the square won't draw either

我正在尝试使用 WASD 键移动一个已经画好的方块。

我不确定该怎么做,所以我查找了一些代码,大约 2 小时后得出了我自己的无法工作的代码。它没有用,但至少它在画我的正方形……或者是。

现在不是了,我不知道为什么,这是我的 JavaScript:

    function initCanvas(){
    var ctx = document.getElementById('my_canvas').getContext('2d');
    ctx.addEventListener("keydown", move, true);

    function move(event){
            //W
            if(event.keyCode == 87){
                    y = y + 20;
            }
            //A
            else if(event.keyCode == 65){
                    x = x - 20;
            }

            //S
            else if(event.keyCode == 83){
                    y = y + 20;
            }

            //D
            else if(event.keyCode == 68){
                    x = x + 20;
            }  
    }

    var x = 0;
    var y = 0;

    ctx.fillStyle = "green";
    ctx.fillRect(x + 20, y + 20, 20, 20);

    }

 window.addEventListener('load', function(event){
    initCanvas();
 });

和HTML/CSS(整页):http://pastebin.com/wjXv5tdK 它可能与事件侦听器有关,因为它似乎没有它也能正常工作。

TL;DR

所以我基本上想要在 canvas 上绘制一个正方形,并让用户使用 WASD 键控制它。

方形不再绘制的原因是您试图将事件侦听器附加到 canvas 上下文,而您只能将侦听器附加到 DOM 对象(canvas).因此,如果您将语句更改为(例如):

    var canvas = document.getElementById('my_canvas');
    canvas.addEventListener("keydown", move, true);

并保留 ctx 语句,canvas 将再次绘制。除非你真的需要 canvas 你最好使用 svg img。

监听文档上的键盘事件,而不是上下文。

document.addEventListener("keydown",move,false);

这里有一些带注释的代码可以让您重新开始:

// create canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

// set canvas to be a tab stop (necessary to give it focus)
canvas.setAttribute('tabindex','0');

// set focus to the canvas
canvas.focus();

// create an x & y indicating where to draw the rect
var x=150;
var y=150;

// draw the rect for the first time
draw();

// listen for keydown events on the document
// the canvas does not trigger key events
document.addEventListener("keydown",handleKeydown,false);

// handle key events
function handleKeydown(e){

  // if the canvas isn't focused,
  // let some other element handle this key event
  if(e.target.id!=='canvas'){return;}

  // change x,y based on which key was down
  switch(e.keyCode){
    case 87: x+=20; break;  // W
    case 65: x-=20; break;  // A
    case 83: y+=20; break;  // S
    case 68: y-=20; break;  // D
  } 

  // redraw the canvas
  draw();
}

// clear the canvas and redraw the rect in its new x,y position
function draw(){
  ctx.clearRect(0,0,cw,ch);
  ctx.fillRect(x,y,20,20);
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<h4>Click in the canvas to have it respond to keys</h4>
<canvas id="canvas" width=300 height=300></canvas>