Overview

Chapter 9. WebGL: 3D application development

This chapter introduces WebGL as a way to build 3D browser applications without plug-ins, emphasizing why it matters for games, simulations, interactive visuals, and other experiences that go beyond the limits of 2D Canvas. It assumes familiarity with Canvas and JavaScript OOP, then frames the chapter around building a complete project from the ground up so readers can learn both the concepts and the practical workflow at the same time.

The first major focus is constructing a reusable WebGL engine. Readers set up the project structure, add supporting scripts for animation, inheritance, matrix math, and WebGL utilities, then build core engine logic for detecting support, storing entities, managing deletion, and defining reusable templates for shapes and objects. Along the way, the chapter explains how WebGL depends on the graphics pipeline, from arrays and buffers through shaders, rasterization, and final screen output, while also showing how shaders are loaded from the DOM and how buffers are created for shape, color, and dimensions.

With the engine in place, the chapter assembles a playable game that uses 2D shapes inside a 3D world. The player can move and shoot, enemies are built from more complex polygon models, and collisions trigger destruction effects that spawn cubes and particles. By the end, the reader has not only a working game but also a practical understanding of WebGL’s rendering model, entity management, matrix handling, and the role of reusable abstractions in 3D application development.

A simple WebGL application called X-Wing created by OutsideOfSociety. He worked on the popular WebGL project http://ro.me.
Get pumped to build your application by going to http://html5inaction.com/app/ch9/ and playing Geometry Destroyer before you build it. Download the source code from Manning’s website at http://manning.com/crowther2/.
Your engine’s file structure should be identical to this figure. We’ve organized it in a manner that’s conducive to learning.
Listing 9.1. index.html—Creating the engine HTML
Result of running the index.html file with CSS and HTML only. In the final screen, the triangular player will appear between the words Geometry and Destroyer.
Step 3: Implement time-saving scripts
Listing 9.4. classes.js—JavaScript inheritance
Step 4: Create base engine logic
Listing 9.5. core.js—Engine startup
Listing 9.6. core.js—Engine entity management
Step 6: Create shape entities with 3D data
Listing 9.7. template.js—Entity default template
Step 7: Add reusable methods that speed up programming and make f- files easier to maintain
If you load up index.html and take a look at your console, it will display no errors or that run.js is missing. Know that if you’ve created a run.js file already, it won’t fire the shown error.
A clean version of the rendering pipeline. Although not a be-all-end-all explanation, it explains the basic steps WebGL goes through as it processes 3D data from start to finish.
Step 1: Create and configure color, vertex, and shape shaders via OpenGL ES
Listing 9.9. index.html—Color, vertex, and shape shaders
Listing 9.10. core.js—Shader setup
Listing 9.11. core.js—Shader retrieval
Step 4: Create shape, color, and dimension buffers for entities
Listing 9.12. template.js—Buffer configuration
Step 1: Use matrices and buffers to visually output information
Listing 9.14. core.js—Drawing shapes (continued)
Listing 9.15. core.js—Drawing shapes (continued)
Step 4: Add matrix helpers to simplify matrix interaction.
Listing 9.17. core.js—Vlad Vukićević utilities
Your code should output the displayed error of “run.js is missing” or no errors at all when running index.html. If you have trouble with the engine files as you proceed, just replace them with the source files from Manning’s website. It’s a nightmare to debug WebGL because of browsers not having easily accessible graphic monitoring tools.
The first thing you’ll do is set up the intro screen logic. After that, you’ll create the triangular player between the words Geometry and Destroyer, which you haven’t seen previously.
Listing 9.18. run.js–Initial game setup
Listing 9.19. run.js—Heads-up display (HUD)
Displays the player’s ship firing a bullet. Notice that both shapes are 2D but drawn in a 3D environment.
Step 3: Create the 2D player entity
Listing 9.20. run.js—Player creation
3d drawing basics
Diagram on the left shows a triangle comprising three points from the player’s matrix data. The right diagram shows a Cartesian coordinate system with x, y, and z.
Demonstrates where a vertex is located on a square
Listing 9.21. run.js—Player update
You should be able to move your player around the screen now. We’ve moved him from between “Geometry Destroyer” to the upper-left corner. Be warned: You can’t shoot bullets with X yet.
Listing 9.22. run.js—Making bullets
Enemies in the game have three major components. First is the large shape shown on the far left. When destroyed, it spawns the next two components: cubes (middle) and particles (far right).
Listing 9.23. run.js—Polygon base
Step 2: Create a complex 3D model
Listing 9.24. run.js—Polygon shape init() prepend
Listing 9.25. run.js—Polygon shape init() prepend
Listing 9.26. run.js—Polygon side, update, and collide
Listing 9.27. run.js—Polygon generator
Step 1: Create a 3D cube particle
Listing 9.28. run.js—Cube shape
Listing 9.29. run.js—Cube indices and color
Listing 9.30. run.js—Cube metadata
Step 4: Generate square particles
Listing 9.31. run.js—Particle generation
Almost every illustration on the bjork.com home page is drawn in a 2D fashion. When they’re moved, you can tell that all the illustrations are 3D.

FAQ

What is WebGL and why is it useful for 3D web applications?WebGL is a browser-based 3D graphics API created by the Khronos Group that lets developers build hardware-accelerated 3D applications without plug-ins. It is useful because it works with modern browsers, uses the GPU for rendering, and avoids the limitations of older plug-in technologies like Flash or Unity-based browser add-ons.
Why does the chapter recommend building your own WebGL engine instead of using a prebuilt one?Building your own engine helps you learn how 3D systems work, create reusable code, and customize features for your application. Prebuilt engines can save time, but they may not support everything you need, so the chapter recommends writing your own when time permits.
What tools or helper scripts does the chapter use to simplify WebGL development?The chapter uses several helper scripts: requestAnimationFrame() for smoother animation, John Resig’s inheritance script for reusable classes, sylvester.js for matrix operations, and webgl_util.js for WebGL utility functions like perspective and matrix handling.
Why does WebGL use shaders, and what do they do?Shaders are small programs that run on the GPU and control how shapes are transformed and colored. In WebGL, shaders handle tasks such as vertex positioning, pixel shading, lighting, and other visual effects.
Why are buffers important in WebGL?Buffers store the shape, color, and dimension data that WebGL sends to the graphics card. Each object typically has its own buffers, which makes it possible to render different 3D entities independently and efficiently.
How does WebGL render 3D data on the screen?WebGL starts with arrays of data, converts them into vertex buffers on the GPU, processes them through vertex and fragment shaders, and then uses the triangle assembler and rasterizer to turn them into pixels on the framebuffer displayed on the screen.
Why does the chapter emphasize triangles when teaching 3D graphics?Triangles are the simplest and most flexible building blocks for 3D shapes. By combining many small triangles, developers can create complex models more easily than with rectangles or other shapes.
Why does Geometry Destroyer use 2D shapes inside a 3D environment?The game uses 2D shapes like the player triangle and bullets because they are simpler to create, but places them in 3D space to demonstrate how 2D assets can be managed and rendered in a WebGL application.
What role do matrices play in the WebGL engine?Matrices are used to move, rotate, and position objects in 3D space. They help WebGL transform model data into screen coordinates so shapes appear in the correct place with the correct orientation.
What browser and hardware requirements does the chapter mention for running the sample application?The chapter recommends using the latest versions of Chrome or Firefox because other browsers may not fully support the needed WebGL features or graphics acceleration. It also warns that some graphics cards may not support WebGL at all, in which case another computer may be necessary.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • HTML5 in Action HTML5 in Action ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • HTML5 in Action HTML5 in Action ebook for free