Open In App

How addEventListener works for keydown on HTML 5 Canvas ?

Last Updated : 30 Jan, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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:




<!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>


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.



Previous Article
Next Article

Similar Reads

HTML DOM addEventListener() Method
The addEventListener() method attaches an event handler to the specified element. Syntax: element.addEventListener(event, function, useCapture) Note: The third parameter use capture is usually set to false as it is not used. Below program illustrates the DOM addEventListener(): Example: &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;D
1 min read
jQuery Keydown() Method
The jQuery keydown() is an inbuilt method that is used to trigger the key-down event whenever the User presses a key on the keyboard. If the key is kept pressed, the event is sent every time the operating system repeats the key. So, Using keydown() method we can detect if any key is on its way down. Syntax: $(selector).keydown(function) Here select
2 min read
AngularJS ng-keydown Directive
The ng-keydown Directive in AngluarJS is used to apply custom behavior on a keydown event. This directive will not be overridden by the element's original onkeydown event. Both the onkeydown event &amp; the ng-keydown Directive will be executed. It is supported by &lt;input&gt;, &lt;select&gt; and &lt;textarea&gt; elements. Syntax: &lt;element ng-k
2 min read
Trigger a keypress/keydown/keyup event in JS/jQuery
In this article, we are going to discuss 2 methods of logging key-presses in web technologies using vanilla JavaScript as well as Jquery. We will also discuss the events related to key-presses in JavaScript. Firstly we have to create a structure so let's make an HTML and CSS layout first. HTML and CSS layout: In the given layout, when an input is m
4 min read
JavaScript addEventListener() with Examples
The addEventListener() is an inbuilt function in JavaScript which takes the event to listen for, and a second argument to be called whenever the described event gets fired. Any number of event handlers can be added to a single element without overwriting existing event handlers.  Syntax:element.addEventListener(event, listener, useCapture);Paramete
2 min read
Difference between addEventListener and onclick in JavaScript
The addEventListener() and onclick both listen for an event. Both can execute a callback function when a button is clicked. However, they are not the same. In this article, we are going to understand the differences between them. addEventListener()The addEventListener() method attaches an event handler to the specified element. Any number of event
3 min read
HTML Canvas Basics
In this article, we will know HTML Canvas Basics, and their implementation through the examples. The HTML "canvas" element is used to draw graphics via JavaScript. The "canvas" element is only a container for graphics. One must use JavaScript to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, text, and addi
5 min read
How to resize an image in an HTML 5 canvas ?
The canvas element is part of HTML 5 and it allows the rendering of 2D shapes and bitmap(also called "raster") images. A canvas actually has two sizes: the size of the element. the size of the element's drawing surface. The element's width and height attributes set both the size of the element and the size of the element's drawing surface. CSS attr
1 min read
HTML canvas lineWidth Property
The HTML canvas lineWidth property is used to set or return the width of the line (thickness of the line). The width of the line is set in terms of pixels. The default value of this property is 1. Syntax: context.lineWidth = number; Property Values: number: This property value indicates the number which specifies the line width in terms of pixels.
2 min read
HTML canvas textAlign Property
The HTML canvas textAlign Property is used to set or return the current alignment for text content, according to the anchor point. Basically, the text will start at that position and the text will end at that specified position. Syntax: context.textAlign="center | end | left | right | start"; Property Values: start: It has a Default. The text start
2 min read
Article Tags :