简体   繁体   English

使用箭头键在画布中移动形状

[英]Moving shapes in canvas with arrow keys

Need help with my code so that it moves the rectangle in initializePlayer to move up, down, left, and right with the keyboard arrows? 在我的代码方面需要帮助,以便它可以在initializePlayer中移动矩形以使用键盘箭头向上,向下,向左和向右移动吗?

function initializePlayer() {
G.context.fillStyle = "purple";
G.context.fillRect(300, 200, 20, 20);
G.context.beginPath(130, 130);
}

function playerMove(dx, dy) {
var canvas = document.getElementById("canvas");
canvas.addEventListener("keydown", keyEventHandler, true); 

}


function keyEventHandler(event) {
if (event.keycode == 38) {
(y - dy > 0)
y -= dy;
}
else if (event.keycode === 40) {  /* Down arrow was pressed */
if (y + dy < HEIGHT)
y += dy;
}
else if (event.keycode === 37) {  /* Left arrow was pressed */
if (x - dx > 0)
x -= dx;
}
else if (event.keycode === 39) {  /* Right arrow was pressed */
if (x + dx < WIDTH)
x += dx;
}
}

function render() {
drawRect(makeRect(300, 200, 20, 20, "purple"))

}

any and all help is appreciated!!! 任何和所有帮助表示赞赏!!!

This code is very messy, format it! 这段代码很乱,格式化它! But there are also some bugs: 但是也有一些错误:

  • Apply the keydown event to the window, not the canvas. keydown事件应用于窗口,而不是画布。 Otherwise the event listener isn't carried out. 否则,将不执行事件侦听器。
  • You used event.keycode . 您使用了event.keycode This property doesn't exist! 该属性不存在! The correct property is event.keyCode . 正确的属性是event.keyCode
  • In keyEventHandler there is a statement that does nothing: (y - dy > 0) I guess you meant if (y - dy > 0) . keyEventHandler有一个不执行任何操作的语句: (y - dy > 0)我猜你是说if (y - dy > 0)

  • To repaint the rectangle when a keydown event occurs, you should call render() at the end of keyEventHandler . 要在发生keydown事件时重新绘制矩形,应在keyEventHandler的末尾调用render()

  • render doesn't work because drawRect and makeRect don't exist. render不起作用,因为drawRectmakeRect不存在。 I expect that this is just a part of your code, but I don't see the sense in this anyway, as you use fixed coordinates? 我希望这只是代码的一部分,但是无论如何我都看不到这种意义,因为您使用的是固定坐标? What about this: 那这个呢:

     function render() { G.context.clearRect(0, 0, WIDTH, HEIGHT); G.context.fillStyle = "purple"; G.context.fillRect(x, y, 20, 20); } 

If you have problems with debugging, I highly recommend you Firebug for Firefox , but every browser also has a built-in console that can be opened with F12. 如果您在调试方面遇到问题,我强烈建议您使用Firefox的Firebug ,但是每个浏览器还具有一个内置控制台,可以使用F12打开该控制台。

window.addEventListener("keydown",function(e){keyEventHandler(e);},false);

instead of 代替

canvas.addEventListener("keydown",keyEventHandler,false);



What's actually working/not working? 实际在起作用/不起作用? I need more information to actually answer the question... :( 我需要更多信息才能真正回答问题... :(

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM