Time for action – accessing the WebGL context
We are going to modify the previous example to add a JavaScript function that is going to check the WebGL availability in your browser (trying to get a handle). This function is going to be called when the page is loaded. For this, we will use the standard DOM onLoad
event.
Open the file
ch1_Canvas.html
in your favorite text editor (a text editor that highlight HTML/JavaScript syntax is ideal).Add the following code right below the
</style>
tag:<script> var gl = null; function getGLContext(){ var canvas = document.getElementById("canvas-element-id"); if (canvas == null){ alert("there is no canvas on this page"); return; } var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"]; for (var i = 0; i < names.length; ++i) { try { gl = canvas.getContext(names[i]); } catch(e) {} if (gl) break; } if (gl == null){ alert("WebGL is not available"); } else{ alert("Hooray! You got a WebGL context"); } } </script>
We need to call this function on the
onLoad
event. Modify your body tag so it looks like the following:<body onLoad ="getGLContext()">
Save the file as
ch1_GL_Context.html.
Open the file
ch1_GL_Context.html
using one of the WebGL supported browsers.If you can run WebGL you will see a dialog similar to the following:
What just happened?
Using a JavaScript variable (gl
), we obtained a reference to a WebGL context. Let's go back and check the code that allows accessing WebGL:
var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"]; for (var i = 0; i < names.length; ++i) { try { gl = canvas.getContext(names[i]); } catch(e) {} if (gl) break; }
The canvas getContext
method gives us access to WebGL. All we need to specify a context name that currently can vary from vendor to vendor. Therefore we have grouped them in the possible context names in the names
array. It is imperative to check on the WebGL specification (you will find it online) for any updates regarding the naming convention.
getContext
also provides access to the HTML5 2D graphics library when using 2d
as the context name. Unlike WebGL, this naming convention is standard. The HTML5 2D graphics API is completely independent from WebGL and is beyond the scope of this book.