Mouseover event for HTML5 canvas

How to connect a mouse manipulator or any event if the drawing of an object on the canvas? For example, I tried this:

var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.beginPath(); //STEP ONE var stepOneRec = ctx.rect(20, 60, 266, 50); ctx.stroke(); stepOneRec.addEventListener("mouseover", function() { alert('it works!'); }); 

One of the sites I was looking at showed a method using Kinetic.js. If this is the only way I will use it, I just assume that there is a way to bind events to drawn elements without additional plugins. Sorry Canvas noob. I made a fiddle with my code here: http://jsfiddle.net/jyBSZ/2/

+7
javascript html5
source share
3 answers

(I started this as a posted comment, then realized that this is the real answer.)

Unfortunately, in javascript on it is your own, you cannot. There are no objects on the canvas, just the canvas as a whole and everything that you used in its context. Plugins, such as kinetic ones, can create objects for you, but the whole point of the canvas is that the browser can view it as one static image.

If you want, you can attach mousemove events to the canvas, track its position and the position in which you painted the material, and imply that it is above β€œthis object” (what plugins do effectively), but it’s all mousemove events on one canvas, not mouseover events on its components. (You can even associate your event with a simulation of the mouseover event for "objects", but underneath it is still based on checking for movement and checking your own settings for the object.)

+4
source share

The objects drawn inside the canvas element are not HTML elements, just pixels, and therefore will not trigger DOM events like HTML elements do.

You will need to track the location of your objects yourself and handle the canvas onmousemove event to determine when the mouse is over one of your drawn objects.

+2
source share

you can use jCanvas, look here

i made a jsfiddle example for your problem.

just change the following callbacks for the desired result

  function mouseOut(layer){ $("#mouse-over-text").html('none options selected'); } function mouseIn(layer){ $("#mouse-over-text").html(getTextForId(layer.name)); } 
+2
source share

All Articles