The next step is to capture and read the mouse coordinates of a user click from the offscreen framebuffer. We can use the standard onmouseup event from the canvas element in our webpage:
const canvas = document.getElementById('webgl-canvas');
canvas.onmouseup = event => {
// capture coordinates from the `event`
};
Since the given event returns the mouse coordinates (clientX and clientY) from the top-left rather than the coordinates with respect to the canvas, we need to leverage the DOM hierarchy to know the total offset that we have around the canvas element.
We can do this with a code fragment inside the canvas.onmouseup function:
let top = 0,
left = 0;
while (canvas && canvas.tagName !== 'BODY') {
top += canvas.offsetTop;
left += canvas.offsetLeft;
canvas = canvas.offsetParent;
}
The following diagram shows how we use...