Next page | Contents page |

Mouse events

There are a number of different kinds of events that may be caused by a mouse moving or being clicked:

In that list "element" means the element on which we have used addEventListener().

We usually only need event listeners for a few of those events, not all of them.

The most common thing we are likely to want to do in a mouse event listener is to get the position of the mouse. This will be needed in every kind of mouse event that we decide to listen to, so it is a candidate for writing a small (reusable) function:


	function getMousePoint(event)
	{
	  return {x:event.offsetX, y:event.offsetY};
	}

Any event object from a mouse event will have 2 properties, offsetX and offsetY which, as usual, are measured from the top left corner of the element we attached our listener to: the canvas. A new bit of syntax here is how to return both values as a simple object. The curly braces make a simple "literal" object that will just have 2 properties, x and y. Calling this function from an event listener would work like this:


	function handleClick(e)
	{
	  let point = getMousePoint(e);
	  // then use point.x and point.y for drawing
	  // ...
	}

There will be more about the other kinds of mouse events in later pages.

Next page | Contents page |