Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raphael canvas (background) onclick event

I have been working with Raphael to create drag and drop shapes on a canvas. I do this using the .drag() function (supplied in the Raphael framework) along with my event functions. I have no issues doing this.

I also have a function that creates a new shape onDblClick, the problem is, I can only attach the event to a shapes, or other elements I create.

Adding events to a shape works like so:

  R = Raphael("canvas", "100%", "100%"),
  R.rect(100, 100, 25, 50).attr({fill: fillColor}).dblclick(myDblClick);

Using the same principle on the canvas doesn't work:

  R = Raphael("canvas", "100%", "100%"),
  R.dblclick(myDblClick);

Does anybody know a way to attach click events to the canvas, i.e. I can click anywhere in the div (excluding shapes) and the event will be triggered.

like image 655
Adam Holmes Avatar asked Nov 11 '10 17:11

Adam Holmes


1 Answers

As the accepted answer didn't work for me (though it did get me on the right track) I thought I would post how I solved it in case there is anybody else in my position...

//Create paper element from canvas DIV
var canvas = $("#Canvas");
paper = Raphael("Canvas", canvas.width(), canvas.height());

//Register Event
$("#Canvas").click(CanvasClick);

//Event Handler
function CanvasClick(e) {
    if (e.target.nodeName == "svg")
    {
       //This will only occur if the actual canvas area is clicked, not any other drawn elements
    }
}
like image 141
musefan Avatar answered Oct 03 '22 14:10

musefan