0

I need to create a canvas that is mostly transparent, ie masks the underlying HTML .. I need mouse events to go to the canvas and the HTML underneath ... The canvas is almost full size of the browser window

Is it possible to do this ?

Update: It needs to be cross browser

...pointer-events: none is not cross browser...is there any other way? –

John
  • 11
  • 3
  • possible duplicate of [Is it possible to let mouse events pass through a canvas layer?](http://stackoverflow.com/questions/6861430/is-it-possible-to-let-mouse-events-pass-through-a-canvas-layer) – Zirak Jul 27 '13 at 20:48
  • @John Please let us know if the linked question solves your problem. – Michael Jul 27 '13 at 20:56
  • no ..it needs to be cross browser...pointer-events: none is not cross browser...is there any other way? – John Jul 27 '13 at 21:16
  • @John Can you please mention this in your question? – Michael Jul 27 '13 at 22:17

1 Answers1

0

It might be possible...and here's a totally untested and ugly attempt at it.

You mention cross-browser compatibility, so jQuery is useful here.

Here's the plan:

  • Have jQuery listen for mouse events on the canvas.
  • When fired, get the mouseX and mouseY.
  • Get a reference to the jQuery event object.
  • Get a set of jQuery objects containing each element at mouseX/mouseY.
  • Use jQuery to trigger the event on each element in that set.

This is a possible starting point...and probably needs tweeking.

Here's some untested code for the click event:

// pre-calc the offsets of the canvas
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;

// on canvas click, 
// get all elements under the click
// and trigger the click event on them

$("#mycanvas").click(function(e){
    mouseX=parseInt(e.clientX-offsetX);
    mouseY=parseInt(e.clientY-offsetY);

    // get a referenct to the jq click event object
    var mEvent=$.Event('click');                       // added '.'

    // get a set of all elements under mouseX/mouseY
    var elements=elementsAtXY(mouseX,mouseY);

    // trigger the event on each element under X/Y
    elements.each(function(){
        $(this).trigger(mEvent);
    });

});



function elementsAtXY(x,y){
    var $elements = $("body *").map(function() {
        var $this = $(this);
        var offset = $this.offset();
        var mleft = offset.left;
        var mtop = offset.top;
        var height = $this.height();
        var width = $this.width();
        var mright = mleft + width;
        var mbottom = mtop + height;

        return (y>=mtop && y <=mbottom) && (x>=mleft && x<=mright) ? $this : null;
    });
    return $elements;
}

If the elements on your page don't move, you could improve performance by pre-calculating the position of each element instead of calculating it during each event.

JSdc
  • 121
  • 1
  • 8
markE
  • 102,905
  • 11
  • 164
  • 176