How to register mouse events on canvas elements?

I want to make a little board game using canvas to get to know javascript and canvas. I can draw a whiteboard perfectly and well, but now I want certain elements to respond to mouse events. I can do it? Or do I need a canvas element for each element of the board that I want to draw, and register a mouse event on each of them?

Or rather, am I hopelessly lost in javascript?

Som background: I am a system developer, and having learned flex and flash, I decided to try my hand at javascript. So don’t pull any punches!

+4
source share
3 answers

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

Now the longer answer: you can do this with a canvas, but then you have to keep track of all your objects and shape yourself and count on which object was clicked, etc., which is probably not what you want . UPDATE: Now there are libraries that can do this for you, for example EaselJS , KineticJS , Paper.js , Fabric.js and some others (see canvas-canvas comparison 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. This is very natural if you are used to working with HTML DOM and events. In addition, it is much more portable - it even works in IE6.

+10
source

You need to do all the tracking yourself, keeping the positions of the elements that you painted on the canvas, their borders, and add a listener for mouse events in the canvas tag.

Here is an example from another thread:

get the click event of each rectangle inside the canvas?

+2
source

Another alternative would be the AI ​​to canvas plugin if you have access to Adobe Illustrator. In this video, they demonstrate the technique of determining the clickable area for your vector shapes: http://visitmix.com/work/ai2canvas/tutorial9.html

0
source

Source: https://habr.com/ru/post/1341751/


All Articles