WebGL Tutorial
What is WebGL?
WebGL was created in 2011.
It was designed as a Web API to provide 2D and 3D drawing inside an HTML canvas element, without the use of a browser plug-in.
Browser Support
The numbers in the table specify the first browser version that fully supports WebGL.
Crome 39 | IE / Edge 11 | Firefox 36 | Safari 8 | Opera 27 |
Sep, 2014 | Des, 2013 | Jan, 2015 | Aug, 2014 | Jan, 2015 |
HTML Canvas Element
In HTML, a <canvas> element looks like this:
<canvas id="myCanvas" width="200" height="100"></canvas>
The <canvas> element must have an id attribute, so it can be referred to by JavaScript.
The width and height attribute is necessary to define the size of the canvas.
You can have multiple <canvas> elements on one HTML page.
By default, the <canvas> element has no border and no content.
To add a border, use a style attribute:
Example
<canvas id="myCanvas" width="200" height="100" style="border:1px solid black;"></canvas>
Try it Yourself »
GPU (Graphical Prosessing Unit)
Computers have a CPU (Central Prosessing Unit).
Screens have a GPU (Graphical Prosessing Unit).
A GPU is a specialized electronic circuit, designed to accelerate the drawing of images in a frame buffer intended for output on a display.
WebGL uses code written in OpenGL ES Shading Language (GLSL). GLSL was design to access the GPU.
WebGL Context
You have to set up a WebGL context before you can start using WebGL:
Example
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
// Get the canvas
const canvas = document.getElementById("myCanvas");
// Initialize the GL context
const gl = canvas.getContext("webgl");
// Only continue if WebGL is available
if (!gl) {
alert("Your browser does not support WebGL.");
}
// Set color buffer to red (1,0,0) and opaque (1)
gl.clearColor(1, 0, 0, 1);
//Set the color with the color buffer
gl.clear(gl.COLOR_BUFFER_BIT);
</script>
Try it Yourself »
Exampe Explained:
- Get a reference to a canvas
- Call getContext() to a WebGL context for the canvas
- Exit if getContext() returns null
- Set values to a color buffer
- Use the color buffer values in the canvas