Raphael canvas (background) onclick event
Solution 1
I would just attach the regular click event (with vanilla javascript, or whatever js framework you are using) to the the canvas node (or the parent node that contains the #canvas element).
With jquery:
//Bound to canvas
$('#canvas').bind('dblclick', myDblClick);
//Bound to parent
$('#canvas').parent().bind('dblclick', myDblClick);
Otherwise, if you are dead-set on using Raphael events, you could draw a rectangle over the entire canvas, and capture click events on that. but that seems like a lot of overhead.
Solution 2
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
}
}
Solution 3
musefans solution with IE compatiblity. Thanks
//Create paper element from canvas DIV
var canvas = $("#Canvas");
paper = Raphael("Canvas", canvas.width(), canvas.height());
$("#canvas").click(canvasClick);
canvasClick: function(e) {
if (e.target.nodeName == "svg" || e.target.nodeName == "DIV" )
},
Related videos on Youtube
![Adam Holmes](https://i.stack.imgur.com/Rq7dY.jpg?s=256&g=1)
Adam Holmes
Bachelor of Science, graduate of The University of Manchester. A freelance Web Developer and enjoy anything that involves computers (A geek you may say).
Updated on May 08, 2022Comments
-
Adam Holmes about 2 years
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.
-
Adam Holmes over 13 yearsThe issue with this is that the event is still called if a shape is clicked on. I only want the background to be applicable to this event.
-
Kayla Rose over 13 yearsInside myDblClick, inspect the event.originalTarget and if it is node a "rect" etc. then fire a custom event. $('#canvas').trigger('dblclick.raphDblClick', {origEvent:event});. Something along those lines should work
-
tokland over 11 yearsUsually you move the
paper
around, sopaper.canvas
should also work.