WebGL Game Development Tutorials

WebGL Book: A WebGL Tutorial Reference Book
Easily understand WebGL and learn how to create 3D worlds and games from scratch.

WebGL Gems is the authorative guide on WebGL programming published by Learning Curve - education for software developers. This book in JavaScript programming series clearly, and in easy to follow language, explains fundamental principles behind programming 3D games using the WebGL framework for JavaScript.

Preorder Now in PDF format for Kindle and get a discount.
WebGL Gems is coming out on April 15th, 2017.
The paperback version will be available via this Amazon page, please bookmark it!

How To Initialize WebGL - Beginner's Tutorial

Initializing 3D context is the first thing you want to do. I am not going to say that this will be an easy WebGL tutorial. Don't get that impression that it is, just because you can copy and paste source code below to initialize WebGL. At the end of the day, the best WebGL tutorial is that which contains working code.

In addition, I recorded this WebGL Initialization tutorial (decrease your volume a bit before viewing! It's one of my first YouTube video tutorials, and I didn't know how to properly adjust audio yet.)

How to Initialize WebGL In 11 Minutes

Here's a direct link to the video tutorial: WebGL initialization (YouTube) tutorial.

The Source Code

You're probably already familiar with 2D graphics capabilities of <canvas> tag, and know how to use the method getContext (I hope!). But 2D is really not why you're reading this tutorial.

Although semi-important, we shouldn't dedicate more time than this on the standard 2D functionality that has nothing to do with WebGL. Therefore, let's initialize a 3D WebGL-enabled canvas.

In this "raw" WebGL tutorial (not using any other libraries) we'll go through the WebGL initialization process. After this, you can move on to explore the rest of WebGL tutorials on this site to explore common WebGL primitives and maybe draw polygons.

How To Initialize WebGL

The process is two-fold. First, we have to get canvas tag into 3D mode and check whether the browser supports it. This is done by passing 'webgl' string to getContext function. A separate function will be created GetWebGLContext for convenience.

Then we need to construct InitializeWebGL function that utilizes GetWebGLContext and puts the puzzle together. These two functions are not native JavaScript functions. They were made up to organize the initialization process.

Getting WebGL Context Object

Similar to the regular initialization <canvas> WebGL counterpart is initialized as follows:

HTML

<canvas id = "view"></canvas>

JavaScript

var canvasId = "view";
var canvas = document.getElementById( canvasId );
var context = canvas.getContext('webgl');

This time instead of "2d" we pass "webgl" to getContext function.

What if getContext returns null?

One common pitfall is when getContext webgl returns null. This might mean two things: WebGL is not enabled in your browser (see how to enable WebGL in any browser), WebGL is not supported by your browser, and the worst case scenaraio: your video card does not support WebGL rendering.

Different browsers, different contexts: (webgl, experimental-webgl, moz-webgl, webkit-3d)

Things aren't always this easy in the world of competing web browser vendors. When new libraries such as WebGL take time to adapt as absolute standards, each browser of course has its own special experimental string for initializing WebGL on canvas.

We must try to check for each one of them in ascending progression to make sure we are offering complete support for old browsers... or browsers missing an update. Below I provide a complete function for initializing WebGL in any browser.

JavaScript Source Code

// Get WebGL context, if standard is not available; fall back on alternatives
function GetWebGLContext( canvas )
{
    return canvas.getContext("webgl") ||            // Standard
    canvas.getContext("experimental-webgl") ||  // Alternative; Safari, others
    canvas.getContext("moz-webgl") ||           // Firefox; mozilla
    canvas.getContext("webkit-3d");             // Last resort; Safari, and maybe others
    // Note that "webgl" is not available as of Safari version <= 7.0.3
    // So we have to fall back to ambiguous alternatives for it,
    // and some other browser implementations.
}

By the way this source code is from WebGL Gems (check it out if you want to master WebGL) and throughout the rest of tutorials on this site we'll initialize WebGL as follows:

var gl = GetWebGLContext( canvas_object );

Initializing WebGL

Initializing just the 3D canvas context is not enough without checking the system for compatibility with 3D graphics. Before 3D canvas is initialized we need to ensure whether we're in a browser that supports WebGL. So let's create the completed version of our initialization process.

JavaScript Source Code

The function below describes a complete WebGL initialization routine. Note that until anything happens, we first query window.WebGLRenderingContext object. If it exists, we can be sure that this browser supports WebGL.

function InitializeWebGL()
{
    var canvas = document.getElementById("gl"); // Handle to canvas tag
    var gl = null;                              // WebGL rendering context
    var extensions = null;                      // Available extensions

    // ! used twice in a row to cast object state to a Boolean value
    if (!!window.WebGLRenderingContext == true)
    {
        // Initialize WebGL rendering context, if available
        if ( gl = GetWebGLContext( canvas ) )
        {
            console.log("WebGL is initialized.");

            // Ensure WebGL viewport is resized to match canvas dimensions
            gl.viewportWidth = canvas.width;
            gl.viewportHeight = canvas.height;

            // Output the WebGL rendering context object
            // to console for reference
            console.log( gl );

            // List available extensions
            console.log( extensions = gl.getSupportedExtensions() );

        } else
            console.log("Your browser doesn't support WebGL.");
        } else
            console.log("WebGL is supported, but disabled :-(");
    }

If your browser supports WebGL this function will initialize WebGL and output supported GL extensions to console. Note that WebGL can also be supported but disabled. If this is the case you have to look into your browser configuration settings to enable it.

If getContext "experimental-webgl" returns null, it means that the browser does not support the experimental mode (this dinosauric mode existed before WebGL was fully supported in browsers). And that's okay because experimental-webgl will eventually become obsolete: just test for "webgl".

Make a Donation

To support this site you can submit a donation to support these free tutorial articles that resemble book chapters. Tons of hard work goes into creating something like this, and your support helps run this website and continue serving useful educational material for WebGL programmers.

WebGL Book: A WebGL Tutorial Reference Book
WebGL Book - A WebGL Tutorial Reference Book

If tutorials on this site are not enough, or you simply like reading from a physical book or a digital device (Kindle, iPad, tablets, etc.) check out WebGL Book. Written by the author of tutorials on this site.

This book is a WebGL tutorial and a reference that guides the reader through the process of setting up and initializing WebGL, drawing 3D primitives and creating 3D computer games.

Preorder Here
© 2017 Copyright WebGL Tutorials (webgltutorials.org)

All content and graphics on this website are the property of webgltutorials.org - please provide a back link when referencing on other sites.