Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I register mouse events on canvas elements?

I want to make a little board game using canvas, to get myself acquainted with javascript and canvas. I can draw the board fine and good, but now I want to make specific elements respond to mouse events. Can I do this? Or do I need a canvas element for each board element I want to draw, and register a mouse event on each of those?

Or, more likely, am I hopelessly lost in javascript?

Som background: I'm a system developer, and after getting to know flex and flash, I've decided to try my hand at some javascript. So don't pull any punches!

like image 801
alexgolec Avatar asked Dec 16 '22 16:12

alexgolec


2 Answers

In short: no. Canvas is just pixels. What you need is SVG (or VML on IE) - or better yet something like Raphaël that would take care of it for you (it uses VML on IE and SVG on everything else).

Now a longer answer: You could do it using canvas, but then you'll have to keep track of all of your objects and shapes yourself and calculate yourself which object was clicked on and so on, which is probably not what you want. UPDATE: there are now libraries that can do it for you, like EaselJS, KineticJS, Paper.js, Fabric.js and some others (see this comparison of canvas libraries for more).

Using Raphaël on the other hand you write code like this:

var circle = r.circle(50, 50, 40);

circle.attr({fill: "red"});

circle.mouseover(function (event) {
    this.attr({fill: "red"});
});

which is most likely what you want. It feels very natural if you're used to working with the HTML DOM and events. Also, it's much more portable - even works in IE6.

like image 63
rsp Avatar answered Dec 19 '22 07:12

rsp


You have to do all the tracking yourself, saving positions of items you've drawn on the canvas, their bounds, and add a listener for mouse events on the canvas tag.

Here's an example from another thread:

get click event of each rectangle inside canvas?

like image 28
Matt King Avatar answered Dec 19 '22 05:12

Matt King