Time for Action: Accessing the WebGL Context

A WebGL context is a handle (more strictly a JavaScript object) through which we can access WebGL functions and attributes. These available features constitute the WebGL API.

We are going to create a JavaScript function that will check whether a WebGL context can be obtained. Unlike other technologies that need to be downloaded into your project, WebGL is already in your browser. In other words, if you are using one of the supported browsers, you don't need to install or include any library.

Let's modify the previous example to add a JavaScript function to check the WebGL availability in your browser. This function is going to be called when the page has loaded. For this, we will use the standard DOM onload event:

  1. Open the ch01_01_canvas.html file in your favorite text editor.
  2. Add the following code right below the closing <style> tag:
<script type="text/javascript">
'use strict';

function init() {
const canvas = document.getElementById('webgl-canvas');

// Ensure we have a canvas
if (!canvas) {
console.error('Sorry! No HTML5 Canvas was found on
this page'
);
return;
}

const gl = canvas.getContext('webgl2');

// Ensure we have a context
const message = gl
? 'Hooray! You got a WebGL2 context'
: 'Sorry! WebGL is not available';

alert(message);
}

// Call init once the document has loaded
window.onload = init;
</script>
  1. Save the file as ch01_02_context.html.
  2. Open the ch01_02_context.html file using one of the WebGL 2 supported browsers.
  3. If you can run WebGL 2, you will see a dialog similar to the following:

Strict Mode

The Strict Mode, declared by 'use strict';, is a feature that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions. For more information, please visit the following link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode.

What just happened? 

Assigning a JavaScript variable (gl), we obtained a reference to a WebGL context. Let's go back and check the code that allows accessing WebGL:

const gl = canvas.getContext('webgl2');

The canvas.getContext method gives us access to WebGL. getContext also provides access to the HTML5 2D graphics library when using 2D as the context name. The HTML5 2D graphics API is completely independent from WebGL and is beyond the scope of this book.