HTML5 Canvas - Handling Mouse Events

Download Javascript File (1.83 kb)

Html5 mouse events handling

In my previous posts, I talked about some basic concepts of HTML5 and Canvas element and do some basic drawing operations with Lines and Rectangles. In this post I am going to discuss handling of mouse events inside canvas elements and utilize those events to create a very basic drawing application that draw lines from position where mouse was clicked to current location of mouse is when you are moving the mouse inside canvas.

Mouse event handlers in canvas

A canvas is like any regular HTML element where you can add an event listener to it. So you will follow the regular process of using addEventListener function to subscribe to mouse events. If you are using jQuery then use the APIs from jQuery to subscibe to events. Following code from my example shows how I attached to mouse events using jQuery.

function setupMouseCapture(canvasId) {
  if (null != canvasElem) {
   canvasElem.mousemove(function (event) {

   canvasElem.mousedown(function (event) {

   canvasElem.mouseup(function (event) {

   canvasElem.mouseleave(function (event) {

Calculating position in mouse event

Mouse event will contain data relative to document or your web page. But when you need to do any drawing operations inside canvas element, you need coordinates relative to canvas element. This means you will have to compensate for offset of canvas element inside your page or document. Following code sample shows how you can calculate position relative to canvas element inside mouse down event.

function onMouseDownInCanvas(event) {
  anchorLocation.x = (event.pageX - canvasElem.position().left);
  anchorLocation.y = (event.pageY - canvasElem.position().top);

Demo JS and Action!

I have created a small demo of the attached JS code. You can view it at Mousy tab in our demo site.

comments powered by Disqus

Blog Tags