Clicking on the canvas

The next step is to capture the mouse coordinates when the user clicks on an object in the scene and reads the color value for these coordinates from the offscreen framebuffer.

For that, we use the standard onmouseup event from the canvas element in our webpage:

var canvas = document.getElementById('my-canvas-id');

canvas.onmouseup = function (ev){
    //capture coordinates from the ev event
    ...
}

There is an extra bit of work to do here given that the ev event does not return the mouse coordinates with respect to the canvas but with respect to the upper-left corner of the browser window (ev.clientX and ev.clientY). Then, we need to bubble up through the DOM getting the location of the elements that are in the DOM hierarchy to ...

Get WebGL Beginner's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.