MENU
.net Powerful JavaScript charts
About
RGraph is a JavaScript charts library based on HTML5 SVG and canvas. RGraph is mature (over 16 years old) and has a wealth of features making it an ideal choice to use for showing charts on your website.

More »

 

Download
Get the latest version of RGraph (version 6.20, 1st December 2024) from the download page. You can read the changelog here. There's also older versions available, minified files and links to cdnjs.com hosted libraries.

Download »

 

License
RGraph can be used for free under the GPL or if that doesn't suit your situation there's an inexpensive (£129) commercial license available.

More »

An example of getting the mouse coordinates on canvas

Written by Richard Heyes, RGraph author, on 1st April 2013

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.