addEventListener for keydown on Canvas

后端 未结 4 1846
忘了有多久
忘了有多久 2020-11-28 06:51

I am trying to make a canvas app that responds to keyboard and mouse input. I have this code:

canvas = document.getElementById(\'canvas\');
canvas.addEventLi         


        
4条回答
  •  一向
    一向 (楼主)
    2020-11-28 07:20

    Edit - This answer is a solution, but a much simpler and proper approach would be setting the tabindex attribute on the canvas element (as suggested by hobberwickey).

    You can't focus a canvas element. A simple work around this, would be to make your "own" focus.

    var lastDownTarget, canvas;
    window.onload = function() {
        canvas = document.getElementById('canvas');
    
        document.addEventListener('mousedown', function(event) {
            lastDownTarget = event.target;
            alert('mousedown');
        }, false);
    
        document.addEventListener('keydown', function(event) {
            if(lastDownTarget == canvas) {
                alert('keydown');
            }
        }, false);
    }
    

    JSFIDDLE

提交回复
热议问题