Download Javascript File (1.83 kb)
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.
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) { getCanvasDrawingCtx(canvasId); if (null != canvasElem) { canvasElem.mousemove(function (event) { onMouseMoveInCanvas(event); }); canvasElem.mousedown(function (event) { onMouseDownInCanvas(event); }); canvasElem.mouseup(function (event) { onMouseUpInCanvas(event); }); canvasElem.mouseleave(function (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); }
I have created a small demo of the attached JS code. You can view it at Mousy tab in our demo site.
How to publish and subscibe events for google wave robots
0x1F is an invalid start of a value
Learn Python: How to ignore SSL verification for HTTP requests
How to host your web site from your home
Automate testing of web page element transition with Selenium
Alert and Confirm pop up using BootBox in AngularJS
AngularJS Grouped Bar Chart and Line Chart using D3
How to lock and unlock account in Asp.Net Identity provider
2022 © Byteblocks, ALL Rights Reserved. Privacy Policy | Terms of Use