a blog for those who code

Monday 2 November 2015

Keyboard and Mouse Interaction to HTML5 Canvas Element

In this post we are going to discuss about the interaction of keyboard and mouse with the HTML5 Canvas element. There could be a lot of instance where you want the user to interact with your canvas element, which can be done through JavaScript event handlers. The events (like mouse click) are called DOM events and we use DOM JavaScript API to create event handlers. Now we will see how to deal with keyboard and mouse event handlers in our code.


Keyboard Events

When you listen to keyboard related events like keydown or keyup the event parameter is passed to the listener function, which will contain of the key that fired the event. In the below snippet we are adding event listener on keydown and keyup. We are also attaching the listener function onKeyDown and onKeyUp which will contain the key that fired the event i.e. 37 for Left Arrow and 39 for Right Arrow.

function onKeyDown(e) {
  if(e.keyCode === 39 ) //right arrow is pressed;
  if(e.keyCode === 37) //left arrow is pressed;
}

function onKeyUp(e) {
  if(e.keyCode === 39 ) //right arrow is pressed;
  if(e.keyCode === 37) //left arrow is pressed;
}

document.addEventListener("keydown", onKeyDown, false);
document.addEventListener("keyup", onKeyUp, false);

Try Key Codes with this Interactive Example : http://codepen.io/codingdefined/pen/JYBXvM

Mouse Events

Detecting mouse events in canvas is very straight forward, we just have to add an event listener to the canvas. In the below snippet we are adding event listener on mouseclick.

document.addEventListener("mouseclick", function(e) {
  //Mouse is clicked
});

Different Mouse Events :

1. mousedown : fired when mouse button is pressed.
2. mouseup : fired when mouse button is released.
3. mouseclick : fired after mousedown and mouseup occurred.
4. mouseover : fired when mouse cursor is moving over the element.
5. mouseleave : fired when mouse leaves the surface of the element.
6. mousemove : fired while mouse moves over the element. The difference between mouseover and mousemove is that only one event is fired in case of mouseover whereas each time mouse moves a new mousemove event is fired.

Please Like and Share the CodingDefined Blog, if you find it knowledgeable and helpful.

1 comment: