Click to choose your tutorial
Tutorial 1: SDK
Tutorial 2: Creating a Window
Tutorial 3: Vulkan Instance
Tutorial 4: Supported Extensions
Tutorial 5: Drawing Points
Tutorial 6: Drawing Lines
Tutorial 7: Drawing Triangles
Tutorial 8: Introduction to Shaders
Tutorial 9: Loading Shaders
Tutorial 10: Using Multiple Shaders
Tutorial 11: Loading 3D Model
Tutorial 12: Displaying 3D Model
Tutorial 13: Vertex Animation
Tutorial 14: Bone Animation
OpenGL Tutorials
site is v0.1a build Sep 11, 2016
Join to be notified of new tutorials
Join

WebGL Tutorial 1 - How To Initialize WebGL

Written by staff. Contact us to submit your article for review.
Sep 13, 2016
tags Tags webgl, init, gpu
Post #41

In this WebGL tutorial we will learn how to set up OpenGL in HTML5 within canvas tag. Even though only setting up a blank drawing area will be explained, important WebGL initialization principles will be covered using the JavaScript (js) language. And then source code will be provided with a browser demo. I use Google Chrome for all of my examples.

Note: To check if your browser supports WebGL, visit http://get.webgl.org/

First, let’s define a basic HTML canvas area. At this point the code has nothing to do with WebGL itself. It’s simply an HTML5 tag:

<canvas id = “gl” width = "640" height = “480"></canvas>

Initializing WebGL in your browser using JavaScript

First, let’s grab an object handle to the canvas tag:

// Get a handle to canvas var canvas = document.getElementById("gl");

You know how in JavaScript we have objects of different types. For example, an array is an object of type Array; it uses the function constructor called Array. A string in JavaScript can be created by using constructor String, and soon. On the other hand WebGLRenderingContext is the newly added object type in JavaScript, that is responsible for interfacing with your graphics adapter (GPU, graphics card) to create 3D graphics in a web browser.

Now, let’s write some JavaScript code that will initialize WebGL. This is done by creating a JavaScript object of aforementioned type WebGLRenderingContext. However, there is no direct way of creating this object using a constructor function, like with the standard JavaScript objects. Instead, we have to use one of the following functions on the canvas object:

var gl = canvas.getContext(“webgl”); // or… var gl = canvas.getContext(“experimental-webgl”); // Alternative, if webgl is not available

There are even more ways to identify a context in different browsers. For example using the literal string moz-webg instead of webgl, we can check for Mozilla’s (Firefox) implementation. And webkit-3d will try to grab GL context from a Webkit based browser. Our final initialization source code will check for these too. I’m just trying to keep things simple for now.

One of these functions will effectively return us the context object to WebGL. If, in fact, your browser supports OpenGL graphics. This context object will be used to call any and all future OpenGL functions. The JavaScript variable name is elegantly named gl.

In the following example we will call the rendering object gl, a simple variable name. Once initialized, we also output the object to the console. This will help us see the properties it contains. These properties show us parameters of the initialized GL context.

Please take a look at the __proto__(or prototype, in browsers where available) object property attached to the WenGL context object gl in its initialized state, by expanding the small arrow in Google Chrome console, after running the WebGL initialization code below. This prototype property contains all initialized OpenGL properties, as well as all available OpenGL functions we can call to create our 3D graphics.

WebGL and OpenGL Extensions

Before we move on to implementing a robust cross-browser WebGL initialization function, let’s briefly talk about OpenGL Extensions.

Traditionally over the years OpenGL has expanded its standard functionality set by adding extensions. An OpenGL extension allows the graphics adapter (GPU) to perform an advanced calculation, processing or rendering technique that you would otherwise have to implement yourself.

In order to grab a list of supported extensions we can use getSupportedExtensions command. This function is attached to the WebGL context object and it is called as follows:

gl_context.getSupportedExtensions();

Note that in the example source code below our WebGL context object is simply called gl.

Some 3D calculation techniques to achieve certain 3D rendering effects have become so popular that an extension was written to ease the ache of writing the code yourself. Not all extensions are available on all video cards and new ones keep being written as the platform continues to evolve.

When I started to learn OpenGL programming back in 2004, I considered the step of checking for extensions to be clunky, and unnecessary. I wished for a standard implementation within the language itself. However, later I realized that since graphics cards always evolve it was a necessary step. A good practice to follow is whenever you want to use an extension, always check if it supported by your video card. Otherwise, fall back to your own implementation, write alternative replacement code that achieves the same effects, or as a last resort, consider not offering that functionality on any adapter that doesn’t support it.

These extensions are written by various programmers, and eventually included in graphics card implementation. Although many popular extensions are available on most modern video cards, robust code should never assume that all or even any extension will be available on absolutely all graphics adapters. If it isn’t present on client’s machine, the code may produce an exception error or in many cases even crash. For this reason, getting a list of supported extensions is a common practice during the initialization stage of WebGL as well as OpenGL on Android, and desktop PCs. We simply need to find out machine’s capability before going further.

Clearing the Screen With a Solid Color

Once the WebGL context object is initialized and stored in gl variable, the following commands are issued as a minimum requirement for clearing the screen with a solid color. In this case we simply chose black (r=0,g=0,b=0). And value of 1.0 for alpha.

The values for all four parameters are in the range between floating point numbers 0.0 and 1.0. This might appear awkward at first. For example red color would be represented as r=1.0, g=0.0, b=0.0 versus the traditional RGB format r=255, g=0, b=0 with proverbial 256 bits per color channel. In other words when it comes to RGB values in OpenGL 1.0 = 255, the highest possible value to represent the red, blue or green channel.

Many, if not most other OpenGL functions, also assume this floating point range convention. Even for values that have nothing to do with colors, but rather vector sizes and other common dimensions. The range between 0.0 and 1.0 is even used to specify texture coordinates and screen coordinates as opposed to pixels.

So having said this, let’s clear the screen with a solid black color:

// Set screen clear color to R, G, B, alpha; where 0.0 is 0% and 1.0 is 100% gl.clearColor(0.0, 0.0, 0.0, 1.0); // Enable color; required for clearing the screen gl.clear(gl.COLOR_BUFFER_BIT); // Clear out the viewport with solid black color gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);

That’s all. In theory, we have now just created an OpenGL context and cleared the screen to black color. Now let’s take a look at the complete source code that accomplishes this task:

Source Code for Cross-Browser WebGL Initialization

In addition to manually becoming familiar with properties of __proto__ property on WebGL context object, let’s initialize WebGL now and print out a list of available GL extensions:

Let’s review WebGL initialization code so far:

<script language = "javascript"> // Get WebGL context, if standard is not available; fall back on alternatives function GetWebGLContext( canvas ) { // Standard return canvas.getContext("webgl") || // Alternative; Safari, others canvas.getContext("experimental-webgl") || // Firefox; mozilla canvas.getContext("moz-webgl") || // Last resort; Safari, and maybe others canvas.getContext("webkit-3d"); // 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 browsers } function InitializeWebGL() { // Get a handle to canvas tag var canvas = document.getElementById("gl"); // WebGL rendering context var gl = null; // Array that will store a list of supported extensions var extensions = null; // ! 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 OpenGL 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() ); // Set screen clear color to R, G, B, alpha; where 0.0 is 0% and 1.0 is 100% gl.clearColor(0.0, 0.0, 0.0, 1.0); // Enable color; required for clearing the screen gl.clear(gl.COLOR_BUFFER_BIT); // Clear out the viewport with solid black color gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight); } else console.log("Your browser doesn't support WebGL."); } else console.log("WebGL is supported, but disabled :-("); } </script>

And there we have it. We have just initialized WebGL in most modern browsers, set the viewport to 640x480 and cleared it out with solid black color.

On my MacBook Air and OSX version of Chrome browser, the console output after running this code is as follows:

WebGL is initialized. > WebGLRenderingContext {} > Array[23] 0: "ANGLE_instanced_arrays" 1: "EXT_blend_minmax" 2: "EXT_frag_depth" 3: "EXT_shader_texture_lod" 4: "EXT_sRGB" 5: "EXT_texture_filter_anisotropic" 6: "WEBKIT_EXT_texture_filter_anisotropic" 7: "OES_element_index_uint" 8: "OES_standard_derivatives" 9: "OES_texture_float" 10: "OES_texture_float_linear" 11: "OES_texture_half_float" 12: "OES_texture_half_float_linear" 13: "OES_vertex_array_object" 14: "WEBGL_compressed_texture_s3tc" 15: "WEBKIT_WEBGL_compressed_texture_s3tc" 16: "WEBGL_debug_renderer_info" 17: "WEBGL_debug_shaders" 18: "WEBGL_depth_texture" 19: "WEBKIT_WEBGL_depth_texture" 20: "WEBGL_draw_buffers" 21: "WEBGL_lose_context" 22: "WEBKIT_WEBGL_lose_context" length: 23

Your WebGL extension list may vary, depending on your video card implementation. Explaining each extension is outside the scope of this tutorial. But for example, WEBGL_depth_texture extension allows us to use the so-called depth textures. A depth texture can be used to simulate shadow casting effect (dynamic shadows.)

A depth texture can be used to store a copy of the current 3D scene using only the Z-axis depth value as opposed to RGB pixel value in a regular texture. It can be used as a depth buffer. Eventually, we will learn how to implement a depth buffer.

For now just know that if you have this extension, then your GPU is capable of creating special types of images that will contain Z-value of each pixel. This is incredibly useful for creating many standard 3D effects.

Congratulations! You have just initialized your first WebGL viewport.

In addition if you've experienced the infamous Chrome's Rats! WebGL hit a snag problem check out this link which contains a video tutorial on how to fix it. If for any reason, this should help get familiar with Chrome's hardware configuration settings. Oh, and also... you can type chrome://gpu into your Chrome's address bar to see how your GPU is configured within the browser.

article tab
Follow OpenGL Tutorials
You will only receive important news about OpenGL tutorial updates.
Who is joining?
  • Programmers You want to stay in touch to receive OpenGL tutorial updates.
  • Game Devs You're a game developer, and you also want to learn more about OpenGL!
  • Supporters You have invested interest in supporting OpenGL tutorial site.
Follow OpenGL Tutorials
Follow