MENU
.net Powerful JavaScript charts

An example of getting the mouse coordinates on canvas

Written by Richard Heyes, RGraph author, on 1st April 2013
A guide explaining how to get hold of the mouse coordinates when clicking on or hovering the mouse over your canvas tag.

Introduction

Finding the X and Y mouse coordinates when you're working with canvas can be a very simple affair:

var mouseX  = e.offsetX;
var mouseY  = e.offsetY;

This however is not particularly portable. For example the Firefox browser does not support the offsetX/Y event properties (update: it does now) so the coordinates have to be worked out another way. Not only that but different browsers have slightly different box models - so things like borders and padding can affect the coordinates.

As an example you can add borders to the canvas below to see the effect on the coordinates.

[No canvas support]

So if your use case is a simple affair where portability is not so important then you could use event.offsetX and event.offsetY. However when portability is a concern or when the client cannot be predicted then a function is necessary that takes all of the different scenarios into account. This is what the RGraph.getMouseXY function does. The function is located in the RGraph.common.core.js file.

An example of the RGraph.getMouseXY() function

Similar to the above example but this time using the RGraph.getMouseXY function which accomodates borders and padding. Again, you can add thick borders to the canvas by clicking here.

[No canvas support]

Download the code

The RGraph.getMouseXY function is part of the RGraph.common.core.js library in the download archive.