Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get clicks through html canvas

Tags:

I'm seeing a lot of questions about how to get the html5 canvas element to receive mouse clicks, I'm using the canvas as an overlay and the mouse clicks aren't going through to the elements below. I'm loading an image into the canvas, and I thought that might be the problem but I've also tried it with an empty canvas and I get the same result.

Here is an example: with the image: http://www.1luckypixel.com/paranormal/canvas_test.html the link goes to google but it's not registering.

It's my understanding that the canvas is transparent to the mouse by default?

like image 353
JoeM05 Avatar asked Sep 01 '10 06:09

JoeM05


1 Answers

If cross browser functionality is not a requirement, then there is an easy solution. On browsers that support it for non SVG elements(webkit, Mozilla and maybe others, but notably not IE), you can use the css property called pointer-events. From the MDN:

"The CSS property pointer-events allows authors to control under what circumstances (if any) a particular graphic element can become the target of mouse events. When this property is unspecified, the same characteristics of the visiblePainted value apply to SVG content.

In addition to indicating that the element is not the target of mouse events, the value none instructs the mouse event to go "through" the element and target whatever is "underneath" that element instead.

Warning: The use of pointer-events in CSS for non-SVG elements is experimental. Currently defined in the CSS3 UI draft specification, there are discussion to postpone it to CSS4."

At the very least, you can use Modernizr to detect pointer-events support and do the opacity trick mentioned in Simon Sarris's answer on browsers that don't support it.

Also, if your application is specific to google maps, you can insert your canvas as a google maps overlay, thus avoiding the problem all together.

Example: http://www.patrick-wied.at/static/heatmapjs/demo/maps_heatmap_layer/gmaps.php

like image 99
Bojin Li Avatar answered Oct 01 '22 02:10

Bojin Li