Related Articles

Related Articles

How addEventListener works for keydown on HTML 5 Canvas ?
  • Last Updated : 30 Jan, 2020

The addEventListener() method is an inbuilt function in JavaScript which takes the event to listen for. The second argument to be called whenever the described event gets fired means the keydown event is fired whenever a key is pressed. This article explains the working of a keydown event listener on a canvas.

The canvas needs to be in focus on to catch key events. It is not possible to assign the keydown event to canvas because it is not possible to focus the canvas with the cursor. So, a workaround for this problem is to bring the canvas to focus.

Below example illustrates the working approach of addEventListner for keydown on canvas:

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html> 
<html>
  
<head>
    <title>
        Working of addeventlistener
        for keydown on a canvas
    </title>
      
    <style
        body {
            display: block;
            margin-top: 8%;
        }
        h1 { 
            color:green;
            text-align:center; 
        }
          
        /* Canvas decoration */
        canvas {
            display: block;
            margin: 0 auto;
            background: green;
            border: 2px solid black;
            height: 300px; 
            width: 300px;
        }
    </style>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
    <canvas id="canvas"></canvas>
      
    <script>
        var lastDownTarget, canvas;
        window.onload = function() {
            canvas = document.getElementById('canvas');
              
            /* For mouse event */
            document.addEventListener('mousedown',
                            function(event) 
            {
                lastDownTarget = event.target;
                alert('Mousedown Event');
            }, false);
              
            /* For keyboard event */
            document.addEventListener('keydown',
                            function(event) 
            {
                if(lastDownTarget == canvas) {
                    alert('Keydown event! Key pressed: '
                                      + event.key);
                }
            }, false);
        }
    </script>
</body>
  
</html>

chevron_right


Output: First, the canvas is brought to focus on using the mousedown event. After the canvas is brought to focus, the keydown event is fired.

full-stack-img




My Personal Notes arrow_drop_up
Recommended Articles
Page :