There are two main events of interest the keydown and keyup events, the names of which should speak for themselves. I often use the key down event to set a boolean value to true, and then the key up to set it back to false, then use those boolean values to change things in an update loop. Another approach would be to make something that is more event driven with or without an update loop.
The basic idea of canvas and keyboard events is that one or more event listeners should be attached to the window object using something like the add event listener method of the window object. When doing so I use the key down or key up event types, and attach a handler method where I define some logic as to what to do when such an event occurs. In this section I will be going over a few basic examples that should work out okay as starting points for canvas and keyboard events.
Very basic and crude, and there is a lot more that needs to be done until I have something that can be called an actual project of some kind. However the basic idea of having something happen when a key is pressed, and something else when it is released is there. This can also be thought of as an event driven kind of example, where user interaction is the only driving force for change of the application state, however getting into the more would be off topic.
Now that we have the basic idea of keydown and keyup events out of the way lest take a look at some of the properties of interest in the event object of a keyboard event.
For this kind of project I started out with a main control.js file that creates a single global variable and returns a single public function to it from within an IIFE. Inside the body of the IIFE I have some private methods including a get canvas relative method that I worked out in another post that I made after starting this post. This method just helps with getting a point that is relative to the upper left corner of the canvas rather than the window of the browser.
I then Have additional helpers that are used to create an input state object, as well as attach event handers to the canvas that is given when calling the main public method that is returned.
When using this module as expected the result is an object that can be used in the body of an update method to know the current status of things when it comes to keys, and a general pointer object that can be updated by mouse or touch events.
Now it is time to try out my control.js module to see if things work as expected.