不能在画布上移动正方形,现在正方形也不会画

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

本文关键字:正方形 移动 不能      更新时间:2023-09-26

我正在尝试使用 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它可能与事件侦听器有关,因为它似乎在没有它的情况下工作。

博士

所以我基本上希望在画布上绘制一个正方形,并让用户使用 WASD 键控制它。

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

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>

正方形不再绘制的原因是您尝试将事件侦听器附加到画布上下文,并且只能将侦听器附加到 DOM 对象(画布)。 因此,如果将语句更改为(例如):

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

并保留 ctx 语句,因为它们是画布将再次绘制的。 除非你真的需要一个画布,否则你最好使用 svg img。