Introduction to WebGL
After Apple created the Canvas element, the Mozilla Foundation began working on a Canvas 3D prototype in 2006, and by 2007, there were implementations of this early version, which would eventually become WebGL. In 2009, a consortium called the Kronos Group began a WebGL Working Group. By 2011, this group had produced the 1.0 version of WebGL, which is based on the OpenGL ES 2.0 API.
As I stated earlier, WebGL was seen as a 3D rendering API that would be used with the HTML5 Canvas element. Its implementation eliminates some of the rendering bottlenecks of the traditional 2D canvas API and gives near-direct access to the computer's GPU. Because of this, it is typically faster to use WebGL to render 2D images to the HTML5 canvas than it is to use the original 2D canvas implementation. However, WebGL is significantly more complicated to use due to the added complexity of three-dimensional rendering. Because of this, several libraries are built on top of WebGL. This allows users to work with WebGL but use a simplified 2D API. If we were writing our game in traditional JavaScript, we might use a library such as Pixi.js or Cocos2d-x for 2D rendering on top of WebGL in order to simplify our code. Right now, WebAssembly uses an implementation of Simple DirectMedia Layer (SDL), and is the library that's used by most developers to write games. This WebAssembly version of SDL is built on top of WebGL and provides high-end performance, but is much easier to use.
Using SDL does not prevent you from also using WebGL directly from within the C++ code compiled into WebAssembly. There are times where we may be interested in directly interacting with WebGL because the features we are interested in are not directly available from within SDL. One example of these use cases is creating custom shaders that allow for special 2D lighting effects.
In this chapter, we will be covering the following topics:
- WebGL and canvas contexts
- An introduction to WebGL shaders
- WebGL and JavaScript