How to combine pressing two keys at the same time to move diagonally?

Alas, the example below does not work.

let block = document.getElementById("test"); let left = 0; let top1 = 0; document.onkeydown = function(event) { if (event.key == "ArrowRight" && event.key == "ArrowUp") { block.style.left = left + "px"; block.style.top = top1 + "px"; top1--; left++; } }; 
 #test { width: 50px; height: 50px; background: orange; position: absolute; left: 0; top: 0; } 
 <div id="test"></div> 

Need a solution on pure js.

  • one
    I know very well that CANVAS knows this perfectly well - what exactly can canvas do? - Grundy
  • @Grundy, I’m not on friendly terms with canvas yet, to give a specific example. But I saw an example where this is implemented ... - Air
  • one
    So what is implemented? - Grundy
  • @Grundy, saw an example .... If I am wrong, tell me what the leading questions are? )))) - Air
  • An example of what you saw? - Grundy

1 answer 1

The idea is that you need to store the state of the buttons, like this:

 let block = document.getElementById("test"); let left = 0; let top1 = 0; let moveRight = false; let moveDown = false; document.onkeydown = function(event) { if (event.key == "ArrowRight") moveRight = true; if (event.key == "ArrowDown") moveDown = true; block.style.left = left + "px"; block.style.top = top1 + "px"; if (moveDown) top1++; if (moveRight) left++; }; document.onkeyup = function(event) { if (event.key == "ArrowRight") moveRight = false; if (event.key == "ArrowDown") moveDown = false; }; 
 #test { width: 50px; height: 50px; background: orange; position: absolute; left: 0; top: 0; } 
 <div id="test"></div>