Robert Robert - 2 months ago 6
Javascript Question

How do I register a click event on the bottom canvas of two layered canvases

I have a game I'm working on which will have multiple canvases. One for the map, another for user interface, another for game objects, etc. The user interface canvas will be the top most canvas, but I'm wondering, if I wanted to register a click event on say, the map layer, how would I do so with the ui canvas being on top of every other canvas? As it stands now, when I click, it only registers the click on the ui canvas, which is what it's supposed to since it's sitting on top of the others. How do I register the click on one of the other canvases instead?

CSS

canvas{
position: absolute;
}

#ui{
bottom: 0;
z-index: 5;
}

#basemap{
z-index: 0;
}


HTML

<canvas id="ui"></canvas>
<canvas id="basemap"></canvas>


JS

var canvases = document.getElementsByTagName("canvas");

for(var i = 0; i < canvases.length; i++){
canvases[i].onclick = function(){
console.log(this);
}
}


Pen

Answer

Set pointer-events to none on the #ui element. This will cause pointer-related events to be ignored by #ui and pass through to the underlying element:

#ui{
    bottom: 0;
    z-index: 5;
    pointer-events: none;
}