Superposition of two canvases + click event

I want to stack two Canvas elements on top of each other. They are used for a game where the lower canvas will display the hexride, while the upper canvas is intended to display problems / orders (mainly arrows or highlighting in hexes - I do not want to redraw the massive hexride a million times) specified by the player.

The canvas is layered by zIndex 1/2.

However, the problem is this: orders displayed on the upper canvas must be drawn in response to the click and mousemove events on the lower canvas.

Obviously, by placing the “orders” canvas on top of the “hexgrid” canvas, any mousemove and click events will no longer fire using the “hexgrid” canvas, since it no longer receives events.

Is there a way to "forward", i.e. distributing events from one element to another element or what is another smart way to solve my problem?

+5
source share
3 answers

Perhaps you need to listen to the event on the root element of the canvas? And after you collect the data from them and process them?

<div onclick="..."> <canvas> <canvas> </div> 

You have experience with such situations, canvases occupy the entire root space, and the coordinates inside the div are the same for the canvas.

+3
source

I extend the event to the next canvas, if the canvases intersect, the coordinates will be the same. A trigger can be created for objects defined inside a closed canvas.

 var Game = {canvas1: undefined, canvas2: undefined}; Game.canvas1 = document.getElementById('canvas1'); Game.canvas1.addEventListener('click', on_canvas_click1, false); Game.canvas2 = document.getElementById('canvas2'); Game.canvas2.addEventListener('click', on_canvas_click2, false); function on_canvas_click1(ev) { //do your stuff on_canvas_click2(ev); } function on_canvas_click2(ev) { var mousePos = getMousePos(Game.canvas2, ev); var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y + " target: " + mousePos.target + " Id: " + mousePos.target.getAttribute("id");; writeMessage(Game.canvas2, message); } function writeMessage(canvas, message) { var context = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width, canvas.height); context.font = '8pt Calibri'; context.fillStyle = 'black'; context.fillText(message, 10, 25); } function getMousePos(canvas, evt) { var rect = canvas.getBoundingClientRect(); return { x: evt.clientX - rect.left, y: evt.clientY - rect.top, target: evt.target }; } 
 <canvas id="canvas1" width="400" height="400" style="border: 1px solid black"></canvas> <canvas id="canvas2" width="400" height="400" style="border: 1px solid black"></canvas> 
+3
source

Perhaps you could just trigger the events of another canvas with document.getElementById ('otherCanvas'). click ()?

0
source

Source: https://habr.com/ru/post/1233020/


All Articles