WebGL - Context: A Friendly Guide for Beginners

Hello there, future WebGL wizards! I'm thrilled to be your guide on this exciting journey into the world of WebGL. As someone who's been teaching computer science for years, I can tell you that WebGL is like a magical paintbrush for your web browser. It lets you create stunning 3D graphics right in your web pages! So, let's roll up our sleeves and dive in, shall we?

WebGL - Context

Creating HTML-5 Canvas Element

First things first, we need a canvas to paint on. In HTML5, we have this nifty thing called the <canvas> element. It's like a blank sheet of paper where we'll draw our WebGL masterpieces.

Let's create our canvas:

<canvas id="myWebGLCanvas" width="800" height="600">
    Your browser does not support HTML5 canvas.
</canvas>

This code creates a canvas that's 800 pixels wide and 600 pixels high. We've given it an ID of "myWebGLCanvas" - think of this as the name tag for our canvas. The text inside the tags is a fallback message for browsers that don't support canvas (but don't worry, most modern browsers do).

Get the Canvas ID

Now that we have our canvas, we need to grab it in our JavaScript code. We do this using the getElementById method. It's like calling our canvas by its name tag.

let canvas = document.getElementById('myWebGLCanvas');

This line finds our canvas element and stores it in a variable called canvas. Easy peasy!

Get the WebGL Drawing Context

Here comes the exciting part - getting our WebGL context. The context is like our set of magical drawing tools that we'll use on our canvas.

let gl = canvas.getContext('webgl');

if (!gl) {
    console.log('WebGL not supported, falling back on experimental-webgl');
    gl = canvas.getContext('experimental-webgl');
}

if (!gl) {
    alert('Your browser does not support WebGL');
}

Let's break this down:

  1. We try to get the WebGL context using getContext('webgl').
  2. If that doesn't work (maybe the browser is a bit older), we try experimental-webgl.
  3. If we still don't get a context, we alert the user that their browser doesn't support WebGL.

WebGLContextAttributes

When we create our WebGL context, we can specify some attributes to customize its behavior. It's like choosing the settings for our magical paintbrush. Here's a table of the available attributes:

Attribute Description Default Value
alpha Canvas contains an alpha buffer true
depth Drawing buffer has a depth buffer of at least 16 bits true
stencil Drawing buffer has a stencil buffer of at least 8 bits false
antialias Drawing buffer performs anti-aliasing true
premultipliedAlpha Page compositor will assume the drawing buffer contains colors with premultiplied alpha true
preserveDrawingBuffer Buffers will not be cleared and will preserve their values until cleared or overwritten false
failIfMajorPerformanceCaveat Context creation will fail if the system performance is low false

To use these attributes, we can pass an object when getting the context:

let contextAttributes = {
    alpha: false,
    depth: true,
    stencil: true,
    antialias: true,
    premultipliedAlpha: false,
    preserveDrawingBuffer: false,
    failIfMajorPerformanceCaveat: false
};

let gl = canvas.getContext('webgl', contextAttributes);

WebGLRenderingContext

Once we have our WebGL context, we can start using its methods and properties to create amazing graphics. The WebGLRenderingContext provides all the WebGL drawing functions.

Here's a simple example that clears the canvas with a nice sky blue color:

if (gl) {
    // Set clear color to sky blue
    gl.clearColor(0.529, 0.808, 0.922, 1.0);

    // Clear the color buffer with specified clear color
    gl.clear(gl.COLOR_BUFFER_BIT);
}

Let's break this down:

  1. gl.clearColor(0.529, 0.808, 0.922, 1.0): This sets the color we'll use to clear the canvas. The numbers represent Red, Green, Blue, and Alpha values, each ranging from 0 to 1.
  2. gl.clear(gl.COLOR_BUFFER_BIT): This actually clears the canvas with our specified color.

And voila! You've just painted your first WebGL masterpiece - a beautiful sky blue canvas!

Remember, this is just the beginning. WebGL has a vast array of functions that allow you to create complex 3D graphics. It's like learning to paint - we start with a blank canvas and a single color, but with practice, you'll be creating intricate 3D worlds in no time!

As we wrap up this introduction to WebGL context, I'm reminded of my first time teaching this concept. I had a student who was so excited about clearing the canvas with different colors, he spent an entire afternoon creating a "color changing mood light" program. It just goes to show, even the simplest concepts can spark incredible creativity!

In our next lesson, we'll dive deeper into WebGL and start drawing some shapes. Until then, happy coding, and may your canvases always be colorful!

Credits: Image by storyset