WebGL Beginner's Guide

WebGL Beginner's Guide
eBook: $26.99
Formats: PDF, PacktLib, ePub and Mobi formats
save 15%!
Print + free eBook + free PacktLib access to the book: $71.98    Print cover: $44.99
save 37%!
Free Shipping!
UK, US, Europe and selected countries in Asia.
Also available on:
Table of Contents
Sample Chapters
  • Dive headfirst into 3D web application development using WebGL and JavaScript.
  • Each chapter is loaded with code examples and exercises that allow the reader to quickly learn the various concepts associated with 3D web development
  • The only software that the reader needs to run the examples is an HTML5 enabled modern web browser. No additional tools needed.
  • A practical beginner's guide with a fast paced but friendly and engaging approach towards 3D web development

Book Details

Language : English
Paperback : 376 pages [ 235mm x 191mm ]
Release Date : June 2012
ISBN : 184969172X
ISBN 13 : 9781849691727
Author(s) : Diego Cantor, Brandon Jones
Topics and Technologies : All Books, Game Development, Beginner's Guides, Web Development, Web Graphics & Video

Table of Contents

Chapter 1: Getting Started with WebGL
Chapter 2: Rendering Geometry
Chapter 3: Lights!
Chapter 4: Camera
Chapter 5: Action
Chapter 6: Colors, Depth Testing, and Alpha Blending
Chapter 7: Textures
Chapter 8: Picking
Chapter 9: Putting It All Together
Chapter 10: Advanced Techniques
  • Chapter 1: Getting Started with WebGL
    • System requirements
    • What kind of rendering does WebGL offer?
    • Structure of a WebGL application
    • Creating an HTML5 canvas
    • Time for action – creating an HTML5 canvas
      • Defining a CSS style for the border
      • Understanding canvas attributes
      • What if the canvas is not supported?
    • Accessing a WebGL context
    • Time for action – accessing the WebGL context
    • WebGL is a state machine
    • Time for action – setting up WebGL context attributes
      • Using the context to access the WebGL API
    • Loading a 3D scene
      • Virtual car showroom
    • Time for action – visualizing a finished scene
    • Summary
    • Chapter 2: Rendering Geometry
      • Vertices and Indices
      • Overview of WebGL's rendering pipeline
        • Vertex Buffer Objects (VBOs)
        • Vertex shader
        • Fragment shader
        • Framebuffer
        • Attributes, uniforms, and varyings
      • Rendering geometry in WebGL
        • Defining a geometry using JavaScript arrays
        • Creating WebGL buffers
          • Operations to manipulate WebGL buffers
        • Associating attributes to VBOs
          • Binding a VBO
          • Pointing an attribute to the currently bound VBO
          • Enabling the attribute
        • Rendering
          • The drawArrays and drawElements functions
      • Putting everything together
      • Time for action – rendering a square
      • Rendering modes
      • Time for action – rendering modes
      • WebGL as a state machine: buffer manipulation
      • Time for action – enquiring on the state of buffers
      • Advanced geometry loading techniques: JavaScript Object Notation (JSON) and AJAX
        • Introduction to JSON – JavaScript Object Notation
          • Defining JSON-based 3D models
          • JSON encoding and decoding
      • Time for action – JSON encoding and decoding
        • Asynchronous loading with AJAX
          • Setting up a web server
          • Working around the web server requirement
      • Time for action – loading a cone with AJAX + JSON
      • Summary
      • Chapter 3: Lights!
        • Lights, normals, and materials
          • Lights
          • Normals
          • Materials
        • Using lights, normals, and materials in the pipeline
          • Parallelism and the difference between attributes and uniforms
      • Shading methods and light reflection models
        • Shading/interpolation methods
          • Goraud interpolation
          • Phong interpolation
        • Light reflection models
          • Lambertian reflection model
          • Phong reflection model
      • ESSL—OpenGL ES Shading Language
        • Storage qualifier
        • Types
        • Vector components
        • Operators and functions
        • Vertex attributes
        • Uniforms
        • Varyings
        • Vertex shader
        • Fragment shader
      • Writing ESSL programs
        • Goraud shading with Lambertian reflections
      • Time for action – updating uniforms in real time
        • Goraud shading with Phong reflections
      • Time for action – Goraud shading
        • Phong shading
      • Time for action – Phong shading with Phong lighting
      • Back to WebGL
        • Creating a program
        • Initializing attributes and uniforms
      • Bridging the gap between WebGL and ESSL
      • Time for action – working on the wall
      • More on lights: positional lights
      • Time for action – positional lights in action
        • Nissan GTS example
      • Summary
        • Chapter 4: Camera
          • WebGL does not have cameras
          • Vertex transformations
            • Homogeneous coordinates
            • Model transform
            • View transform
            • Projection transform
            • Perspective division
            • Viewport transform
          • Normal transformations
            • Calculating the Normal matrix
          • WebGL implementation
            • JavaScript matrices
            • Mapping JavaScript matrices to ESSL uniforms
            • Working with matrices in ESSL
          • The Model-View matrix
            • Spatial encoding of the world
              • Rotation matrix
              • Translation vector
              • The mysterious fourth row
          • The Camera matrix
            • Camera translation
          • Time for action – exploring translations: world space versus camera space
            • Camera rotation
          • Time for action – exploring rotations: world space versus camera space
            • The Camera matrix is the inverse of the Model-View matrix
            • Thinking about matrix multiplications in WebGL
          • Basic camera types
            • Orbiting camera
            • Tracking camera
              • Rotating the camera around its location
              • Translating the camera in the line of sight
              • Camera model
          • Time for action – exploring the Nissan GTX
          • The Perspective matrix
            • Field of view
            • Perspective or orthogonal projection
          • Time for action – orthographic and perspective projections
          • Structure of the WebGL examples
            • WebGLApp
            • Supporting objects
            • Life-cycle functions
              • Configure
              • Load
              • Draw
            • Matrix handling functions
              • initTransforms
              • updateTransforms
              • setMatrixUniforms
          • Summary
          • Chapter 5: Action
            • Matrix stacks
            • Animating a 3D scene
              • requestAnimFrame function
              • JavaScript timers
            • Timing strategies
              • Animation strategy
              • Simulation strategy
              • Combined approach: animation and simulation
              • Web Workers: Real multithreading in JavaScript
            • Architectural updates
              • WebGLApp review
              • Adding support for matrix stacks
              • Configuring the rendering rate
              • Creating an animation timer
            • Connecting matrix stacks and JavaScript timers
            • Time for action – simple animation
            • Parametric curves
              • Initialization steps
              • Setting up the animation timer
              • Running the animation
              • Drawing each ball in its current position
            • Time for action – bouncing ball
            • Optimization strategies
              • Optimizing batch performance
              • Performing translations in the vertex shader
            • Interpolation
              • Linear interpolation
              • Polynomial interpolation
              • B-Splines
            • Time for action – interpolation
            • Summary
            • Chapter 6: Colors, Depth Testing, and Alpha Blending
              • Using colors in WebGL
              • Use of color in objects
                • Constant coloring
                • Per-vertex coloring
                • Per-fragment coloring
              • Time for action – coloring the cube
              • Use of color in lights
                • Using multiple lights and the scalability problem
                  • How many uniforms can we use?
                  • Simplifying the problem
              • Architectural updates
                • Adding support for light objects
                  • Improving how we pass uniforms to the program
              • Time for action – adding a blue light to a scene
                • Using uniform arrays to handle multiple lights
                  • Uniform array declaration
                  • JavaScript array mapping
              • Time for action – adding a white light to a scene
              • Time for action – directional point lights
              • Use of color in the scene
                • Transparency
                • Updated rendering pipeline
              • Depth testing
                • Depth function
              • Alpha blending
                • Blending function
                • Separate blending functions
                • Blend equation
                • Blend color
                • WebGL alpha blending API
                • Alpha blending modes
                  • Additive blending
                  • Subtractive blending
                  • Multiplicative blending
                  • Interpolative blending
              • Time for action – blending workbench
              • Creating transparent objects
              • Time for action – culling
              • Time for action – creating a transparent wall
              • Summary
              • Chapter 7: Textures
                • What is texture mapping?
                • Creating and uploading a texture
                • Using texture coordinates
                • Using textures in a shader
                • Time for action – texturing the cube
                • Texture filter modes
                • Time for action – trying different filter modes
                  • NEAREST
                  • LINEAR
                • Mipmapping
                  • NEAREST_MIPMAP_NEAREST
                  • LINEAR_MIPMAP_NEAREST
                  • NEAREST_MIPMAP_LINEAR
                  • LINEAR_MIPMAP_LINEAR
                • Generating mipmaps
              • Texture wrapping
              • Time for action – trying different wrap modes
                • CLAMP_TO_EDGE
                • REPEAT
                • MIRRORED_REPEAT
              • Using multiple textures
              • Time for action – using multitexturing
              • Cube maps
              • Time for action – trying out cube maps
              • Summary
                • Chapter 8: Picking
                  • Picking
                  • Setting up an offscreen framebuffer
                    • Creating a texture to store colors
                    • Creating a Renderbuffer to store depth information
                    • Creating a framebuffer for offscreen rendering
                  • Assigning one color per object in the scene
                  • Rendering to an offscreen framebuffer
                  • Clicking on the canvas
                  • Reading pixels from the offscreen framebuffer
                  • Looking for hits
                  • Processing hits
                  • Architectural updates
                  • Time for action – picking
                    • Picker architecture
                  • Implementing unique object labels
                  • Time for action – unique object labels
                  • Summary
                  • Chapter 9: Putting It All Together
                    • Creating a WebGL application
                    • Architectural review
                    • Virtual Car Showroom application
                      • Complexity of the models
                      • Shader quality
                      • Network delays and bandwidth consumption
                    • Defining what the GUI will look like
                      • Adding WebGL support
                    • Implementing the shaders
                    • Setting up the scene
                    • Configuring some WebGL properties
                      • Setting up the camera
                      • Creating the Camera Interactor
                      • The SceneTransforms object
                      • Creating the lights
                      • Mapping the Program attributes and uniforms
                      • Uniform initialization
                    • Loading the cars
                      • Exporting the Blender models
                      • Understanding the OBJ format
                      • Parsing the OBJ files
                      • Load cars into our WebGL scene
                    • Rendering
                    • Time for action – customizing the application
                    • Summary
                    • Chapter 10: Advanced Techniques
                      • Post-processing
                        • Creating the framebuffer
                        • Creating the geometry
                        • Setting up the shader
                      • Architectural updates
                      • Time for action – testing some post-process effects
                      • Point sprites
                      • Time for action – using point sprites to create a fountain of sparks
                      • Normal mapping
                      • Time for action – normal mapping in action
                      • Ray tracing in fragment shaders
                      • Time for action – examining the ray traced scene
                      • Summary

                      Diego Cantor

                      Diego Cantor is a software engineer with experience in government, education, finance, enterprise resource planning (ERP) and data warehouse (DWH) projects. He has also been appointed as instructor at the Faculty of Engineering at the Universidad de los Andes (Colombia) in the department of Systems Engineering. He did an internship at the CREATIS lab in Lyon, France. During that internship he implemented a component model based on the OSGi standards for medical imaging applications. After that, he did an internship at the Australian e-Health Research Centre in Brisbane, Australia, working on imaging analysis techniques and applying them to the study of Alzheimer's disease. During his graduate studies, Diego worked on the processing of medical images (MRI) in 3D. This work led him to work with VTK and ITK and later on to research on technologies to improve state of the art medical imaging visualization and medical simulation systems. Currently he is a PhD student at the University of Western Ontario in Canada. There, he works on computational methods to correlate MRI to digital histology imaging. Diego speaks English, Spanish, and French.

                      Brandon Jones

                      Brandon Jones has been developing WebGL demos since the technology first began appearing in browsers in early 2010. He finds that it’s the perfect combination of two aspects of programming that he loves, allowing him to combine eight years of web development experience and a life-long passion for real-time graphics. Brandon currently works with cutting-edge HTML5 development at Motorola Mobility.
                      Sorry, we don't have any reviews for this title yet.

                      Code Downloads

                      Download the code and support files for this book.

                      Submit Errata

                      Please let us know if you have found any errors not listed on this list by completing our errata submission form. Our editors will check them and add them to this list. Thank you.


                      - 4 submitted: last submission 03 Feb 2014

                      Errata type: Code | Page number: 78

                      The color picker now remember the last color selected. Also the Lambert sphere exercise has been updated with the missing y-axis slider.
                      The updated working exercises can be found at WebGL Beginner’s Guide – Examples.
                      The repository with the source code has been updated at Download the source code.


                      Errata type: Code | Page number:80

                      The code line

                      gl.uniform3f(prg.uLightDirection, 0.0, 0.0, -1.0)

                      in step 7 of page 80, should be

                      gl.uniform3f(prg.uLightDirection, 0.0, -1.0, -1.0)

                      Errata type: Code | Page number: 96

                      The code has been updated in the BitBucket repository, at:



                      The code example has been updated at:



                      Errata Type : Technical | Page number: 61

                      In the Normals section for calculating the normals the Vector values for v1 and v2 in the explanation have been mentioned incorrectly. The values vector v1 should be p1 - p0 and v2 should be p2 - p0. 

                      Sample chapters

                      You can view our sample chapters and prefaces of this title on PacktLib or download sample chapters in PDF format.

                      Frequently bought together

                      WebGL Beginner's Guide +    Learning  jQuery : Better Interaction Design and Web Development with Simple JavaScript Techniques =
                      50% Off
                      the second eBook
                      Price for both: €21.50

                      Buy both these recommended eBooks together and get 50% off the cheapest eBook.

                      What you will learn from this book

                      • Understand the structure of a WebGL application
                      • Build and render 3D objects with WebGL
                      • Load complex models using JSON and AJAX
                      • Set up a lighting model using shaders, physics of light reflection, and lighting strategies
                      • Create a camera and use it to move around a 3D scene
                      • Use texturing, lighting and shading techniques to add greater realism to 3D scenes
                      • Implement selection of objects in a 3D scene with the mouse
                      • Advanced techniques to create more visually complex and compelling scenes

                      In Detail

                      WebGL is a new web technology that brings hardware-accelerated 3D graphics to the browser without installing additional software. As WebGL is based on OpenGL and brings in a new concept of 3D graphics programming to web development, it may seem unfamiliar to even experienced Web developers.

                      Packed with many examples, this book shows how WebGL can be easy to learn despite its unfriendly appearance. Each chapter addresses one of the important aspects of 3D graphics programming and presents different alternatives for its implementation. The topics are always associated with exercises that will allow the reader to put the concepts to the test in an immediate manner.

                      WebGL Beginner's Guide presents a clear road map to learning WebGL. 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 WebGL topics, including drawing, color, texture, transformations, framebuffers, light, surfaces, geometry, and more. With each chapter, you will “level up” your 3D graphics programming skills. This book will become your trustworthy companion filled with the information required to develop cool-looking 3D web applications with WebGL and JavaScript.


                      This book is a step-by-step tutorial that includes complete source code for all of the examples covered. Every chapter builds on top of the previous one thereby giving the reader an immediate feeling of progression. Each block of code is explained, and 3D web development concepts are diagrammed and covered in detail.

                      Who this book is for

                      This book is written for JavaScript developers who are interested in 3D web development. A basic understanding of the DOM object model and the jQuery library is ideal but not required. No prior WebGL knowledge is expected.

                      Code Download and Errata
                      Packt Anytime, Anywhere
                      Register Books
                      Print Upgrades
                      eBook Downloads
                      Video Support
                      Contact Us
                      Awards Voting Nominations Previous Winners
                      Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
                      Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software