...Back to blog index

WebGL 1 to 2 Changes: Part 1

In the upcoming posts, we will cover the changes in WebGL between version 1 and 2. Rather then overwhelm with the complete changeset, for this first post I will show how to update an existing example to the newer version of WebGL.

Starting with the Julia Set example, we will alter the code to work using WebGL 2.

Our first step is to tell the canvas context that we are using the newer API:

gl = canvas.getContext('webgl2');

Next, to make the code easier to read, I am putting the shaders into separate external files:

    <script src="./julia-set.vs"></script>
    <script src="./julia-set.fs"></script>

The vertex shader contents are:

let vsSource = `#version 300 es
in vec3 aVertexPosition;

out vec2 position;
void main(void) {
    position = vec2(aVertexPosition.xy);
    gl_Position = vec4(position.xy, 0.0, 1.0);
}`;

Here we are assigning the shader to a template literal for later use. The other changes are:

#version 300 es
The version of the shading language has changed to 3.0 and must be specified in the very first line of the shader. No exceptions. The keywords
attribute
varying
have been changed to
in
out
respectively. This makes sense to me and is easier to understand/remember IMO.
in
refers to input and
out
here refers to output. I mention here because
varying
had multiple meanings depending on context.

Next, here is the full fragment shader:

let fsSource = `#version 300 es
in highp vec2 position;
const int MAX_ITERATIONS = 150;
const highp float LIGHTNESS_FACTOR = 2.0;
out highp vec4 outputColor;

void main(void) {
    highp vec2 z = vec2(position.x, position.y);
    highp vec2 c = vec2(-.8,-.2);
    highp vec4 color = vec4(0.0, 0.0, 0.0, 1.0);

    for (int i = 0; i < MAX_ITERATIONS; i++)
    {
        z = vec2(z.x*z.x - z.y*z.y, 2.0*z.x*z.y) + c;

        if (dot(z, z) > 4.0)
        {
            highp float f =  LIGHTNESS_FACTOR*float(i) / float(MAX_ITERATIONS);
            color = vec4(vec3(0.1, 0.1, 1.0)*f, 1.0);
            break;
        }
    }
    outputColor = color;
}`;

Ignoring the logic which remains the same as for version 1, the changes here are:

   varying highp vec2 position;
This variable has been changed to an input.
out highp vec4 outputColor;
This variable is new and replaces the previous usage of
gl_FragColor

which is now deprecated. The name can be anything (except keywords of course) as long as we let the shader know that it is output.

For this example, those are all the changes needed to get a working program. We see the generated Julia Set as below.

WebGL 2: Julia Set

Full source code is available at https://github.com/bdanchilla/beginningwebgl/tree/master/webgl2/julia-set

...Back to blog index