Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Real-Time 3D Graphics with WebGL 2 - Second Edition

You're reading from  Real-Time 3D Graphics with WebGL 2 - Second Edition

Product type Book
Published in Oct 2018
Publisher Packt
ISBN-13 9781788629690
Pages 500 pages
Edition 2nd Edition
Languages
Authors (2):
Farhad Ghayour Farhad Ghayour
Profile icon Farhad Ghayour
Diego Cantor Diego Cantor
Profile icon Diego Cantor
View More author details
Toc

Table of Contents (14) Chapters close

Preface 1. Getting Started 2. Rendering 3. Lights 4. Cameras 5. Animations 6. Colors, Depth Testing, and Alpha Blending 7. Textures 8. Picking 9. Putting It All Together 10. Advanced Techniques 11. WebGL 2 Highlights 12. Journey Ahead 13. Other Books You May Enjoy

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

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime