In Javascript, how do I tell if a user is pressing two keys at the same time?

前端 未结 4 1934
轻奢々
轻奢々 2021-02-09 13:30

In Javascript, how do I tell if a user is pressing two keys at the same time?

For example, I have drawn a circle in the middle of the screen. I want to move it up while

4条回答
  •  名媛妹妹
    2021-02-09 14:30

    Maybe you can do it by keeping track of keydown and keyup event for each key and you'll know if two keys are being held at the same time.

    Sample pseudo-code:

    var keydown = {};
    
    function onkeydown(event) {
       keydown[event.key] = true;
    }
    
    function onkeyup(event) {
       keydown[event.key] = false;
    }
    
    // in some function at some other places
    
    if (keydown['up'] && keydown['right']) {
      move_diagonal('up', 'right');
    }
    elseif (keydown['up'] && keydown['left']) {
      move_diagonal('up', 'left');
    }
    elseif .. blah blah
    

提交回复
热议问题