WebGL Textures & Vertices

Beginner's Guide

Page Thirty Five

Obtain a WebGLContext

The controller constructor first calls method getGLContext(canvas). Method getGLContext(canvas) returns a reference to a WebGLContext, suitable for rendering to the canvas with WebGL. The controller saves the WebGLContext reference, to the property named gl. Every WebGL method, constant, and feature, requires a valid WebGLContext. If the browser doesn't support WebGL then getGLContext(canvas) displays an error message, and returns null.

First the GLControl constructor obtains a reference to the HTML5 canvas as follows.

var cv = document.getElementById('cv');

The constructor passes a reference to the HTML5 canvas to method getGLContext(canvas). If you've used the HTML5 2D context, then obtaining the 3D context may look familiar. In most cases canvas.getContext('webgl') returns a valid WebGLContext. However at this time, some browsers name the 3D context experimental-webgl, webkit-3d, or moz-webgl. Therefore getGLContext(canvas) iterates over a list of possible context names. After finding a valid WebGLContext, method getGLContext(canvas) breaks and returns the context.

If the WebGLContext is valid, then GLControl saves a reference to the property named gl. However if the value returned from getGLContext() is null, then code displays an error message and exits. The method viewError(String,controller) displays a message to an element on the current Web page. The following listing includes the entire source code for getGLContext(canvas).

getGLContext: function(canvas){
// Windows Phone 8.1
// default browser 
// uses 'experimental-webgl'.
var a3D = ['webgl', 

var glContext = null;

try {

// Iterate over our array.
for (var i = 0; i < a3D.length; i++) {  
 // Try to obtain a 3D context.
 glContext = canvas.getContext(a3D[i]);
 // If we found a context,
 // then break out of the loop.
  if (glContext != null) {

// If there's an error,
// then display it.
catch(err) {    

 // WebGLContext or null.
 return glContext;

Listing 27: getGLContext(canvas)

WebGL Beginner's Guide Introduction WebGL Beginner's Guide
Copyright © 2015 Seven Thunder Software. All Rights Reserved.