Chapter 5. Interaction
Like any online medium, WebGL is a tripod that stands on three legs: graphics, animation, and interaction. Our examples thus far have made very limited use of interaction. We handled mouse clicks in the canvas to toggle animation states; we used controls on the web page to change behaviors in the WebGL scene. But we can go way beyond this. We can click and drag on items in the scene itself, triggering other behaviors. We can also navigate within the scene by manipulating the camera. Furthermore, we can combine these capabilities with animated tweens to give our interactivity a rich, organic feel.
As an experienced web developer, you probably take interaction for granted. Browsers automatically perform hit detection—the process of finding out which element the mouse pointer is over—for you; you simply need to register mouse event handlers for your DOM elements and controls. However, WebGL is only a drawing system and, as such, has no built-in support for hit detection. You need to build that yourself. Thankfully, Three.js gives us the support we need so that we can tell when the mouse is over an object. We will lean on that to implement rollovers, clicks, and dragging, as well as camera navigation. We will also use Tween.js to combine interaction with animation for some nice UI effects. Let’s get into it.
Hit Detection, Picking, and Projection
Hit detection is a special case of the more general 3D graphics concept of picking, the process of determining if two ...