Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 canvas Mouseover event

How do I bind a mouseover or any event for that matter to a drawn object on the canvas? For instance, 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!'); });

On one site I looked at it showed a method using Kinetic.js. If that's the only way, I'll use it, I just assume that there's a way to bind events to drawn elements without extra plug-ins. Sorry Canvas noob. I made a fiddle with my code here: http://jsfiddle.net/jyBSZ/2/

like image 207
user2287474 Avatar asked Sep 27 '13 16:09

user2287474


2 Answers

(I started this as a posted comment, then realized it's an actual answer.)

Unfortunately, in javascript on it's own, you can't. There are no canvas objects, just the canvas as a whole, and whatever you drew on to its context. Plugins like kinetic can make objects for you, but the whole point of canvas is that the browser can think of it as a single static image.

If you want to, you can bind mousemove events to the canvas, track its position and the position where you drew stuff, and imply on your own that it's over "that object" (effectively what the plugins do), but it's all mousemove events on a single canvas rather than mouseover events on components of it. (You could even make your event binding simulate a mouseover event for the "objects", but underneath, it's still based on checking movement and checking your own object setup.)

like image 188
Scott Mermelstein Avatar answered Oct 29 '22 15:10

Scott Mermelstein


The objects drawn within a canvas element are not HTML elements, just pixels, and therefore will not throw DOM events the way that HTML elements would.

You would need to track the locations of your objects yourself and handle the canvas' onmousemove event in order to determine when the mouse is over one of your drawn objects.

like image 41
Rob Hardy Avatar answered Oct 29 '22 16:10

Rob Hardy