Skip to content
Related Articles

Related Articles

How addEventListener works for keydown on HTML 5 Canvas ?

Improve Article
Save Article
  • Last Updated : 30 Jan, 2020
Improve Article
Save Article

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:


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

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.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!