Book Image

Real-Time 3D Graphics with WebGL 2 - Second Edition

By : Farhad Ghayour, Diego Cantor
5 (1)
Book Image

Real-Time 3D Graphics with WebGL 2 - Second Edition

5 (1)
By: Farhad Ghayour, Diego Cantor

Overview of this book

As highly interactive applications have become an increasingly important part of the user experience, WebGL is a unique and cutting-edge technology that brings hardware-accelerated 3D graphics to the web. Packed with 80+ examples, this book guides readers through the landscape of real-time computer graphics using WebGL 2. Each chapter covers foundational concepts in 3D graphics programming with various implementations. Topics are always associated with exercises for a hands-on approach to learning. This book presents a clear roadmap to learning real-time 3D computer graphics with WebGL 2. Each chapter starts with a summary of the learning goals for the chapter, followed by a detailed description of each topic. The book offers example-rich, up-to-date introductions to a wide range of essential 3D computer graphics topics, including rendering, colors, textures, transformations, framebuffers, lights, surfaces, blending, geometry construction, advanced techniques, and more. With each chapter, you will "level up" your 3D graphics programming skills. This book will become your trustworthy companion in developing highly interactive 3D web applications with WebGL and JavaScript.
Table of Contents (14 chapters)

Clicking on the Canvas

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...