Beginning WebGL step-by-step tutorial

I’ve put together this very basic WebGL tutorial that takes you through the process of initialising WebGL, creating shaders, creating a triangle and then showing it on the screen as a one-off render. I haven’t used external JavaScript libraries like sylvester because I wanted this tutorial to be self-contained. Because I don’t apply translations or rotations there’s no need for further Matrix operations.

All functions calls link to the OpenGL ES documentation for easy reference.

The source file for this tutorial can be found here.

<!--
Define a simple GLSL (OpenGL Shading Language) fragment shader.
More info: http://en.wikipedia.org/wiki/GLSL
-->
<script id="shader-fs" type="x-shader/x-fragment">
void main(void) {
gl_FragColor = vec4(0.6, 0.0, 0.0, 1.0);
}
</script>
<!--
Define a simple GLSL (OpenGL Shading Language) vertex shader.
More info: http://en.wikipedia.org/wiki/GLSL
-->
<script id="shader-vs" type="x-shader/x-vertex">
attribute vec3 vertexPosition;

uniform mat4 modelViewMatrix;
uniform mat4 perspectiveMatrix;

void main(void) {
gl_Position = perspectiveMatrix * modelViewMatrix * vec4(vertexPosition, 1.0);
}
</script>
<script type="text/javascript">
window.onload = loadScene;

/**
* Initialises WebGL and creates the 3D scene.
*/
function loadScene()
{
// Get the canvas element
var canvas = document.getElementById("webGLCanvas");
// Get the WebGL context
var gl = canvas.getContext("experimental-webgl");
// Check whether the WebGL context is available or not
// if it's not available exit
if(!gl)
{
alert("There's no WebGL context available.");
return;
}
// Set the viewport to the canvas width and height
gl.viewport(0, 0, canvas.width, canvas.height);

// Load the vertex shader that's defined in a separate script
// block at the top of this page.
// More info about shaders: http://en.wikipedia.org/wiki/Shader_Model
// More info about GLSL: http://en.wikipedia.org/wiki/GLSL
// More info about vertex shaders: http://en.wikipedia.org/wiki/Vertex_shader

// Grab the script element
var vertexShaderScript = document.getElementById("shader-vs");
// Create a vertex shader object
var vertexShader = gl.createShader(gl.VERTEX_SHADER);
// Load the shader with the source strings from the script element
gl.shaderSource(vertexShader, vertexShaderScript.text);
// Compile the shader source code string
gl.compileShader(vertexShader);
// Check if the shader has compiled without errors
if(!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
alert("Couldn't compile the vertex shader");
// Clean up
gl.deleteShader(vertexShader);
return;
}

// Load the fragment shader that's defined in a separate script
// block at the top of this page.
// More info about fragment shaders: http://en.wikipedia.org/wiki/Fragment_shader
var fragmentShaderScript = document.getElementById("shader-fs");
// Create a fragment shader object
var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
// Load the shader with the source strings from the script element
gl.shaderSource(fragmentShader, fragmentShaderScript.text);
// Compile the shader source code string
gl.compileShader(fragmentShader);
// Check if the shader has compiled without errors
if(!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
alert("Couldn't compile the fragment shader");
// Clean up
gl.deleteShader(fragmentShader);
return;
}

// Create a shader program. From the OpenGL documentation:
// A program object is an object to which shader objects can be attached.
// This provides a mechanism to specify the shader objects that will be linked to
// create a program. It also provides a means for checking the compatibility of the
// shaders that will be used to create a program (for instance, checking the
// compatibility between a vertex shader and a fragment shader).
gl.program = gl.createProgram();
// Attach the vertex shader to the program
gl.attachShader(gl.program, vertexShader);
// Attach the fragment shader to the program
gl.attachShader(gl.program, fragmentShader);
// Before we can use the shaders for rendering, we have to link the program
// object.
gl.linkProgram(gl.program);
// Check the status of the link operation to see if it was linked without
// errors.
if (!gl.getProgramParameter(gl.program, gl.LINK_STATUS)) {
alert("Unable to initialise shaders");
// Clean up
gl.deleteProgram(gl.program);
gl.deleteProgram(vertexShader);
gl.deleteProgram(fragmentShader);
return;
}
// Install the program as part of the current rendering state
gl.useProgram(gl.program);
// Get the vertexPosition attribute from the linked shader program
var vertexPosition = gl.getAttribLocation(gl.program, "vertexPosition");
// Enable the vertexPosition vertex attribute array. If enabled, the array
// will be accessed an used for rendering when calls are made to commands like
// gl.drawArrays, gl.drawElements, etc.
gl.enableVertexAttribArray(vertexPosition);

// Clear the color buffer (r, g, b, a) with the specified color
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Clear the depth buffer. The value specified is clamped to the range [0,1].
// More info about depth buffers: http://en.wikipedia.org/wiki/Depth_buffer
gl.clearDepth(1.0);
// Enable depth testing. This is a technique used for hidden surface removal.
// It assigns a value (z) to each pixel that represents the distance from this
// pixel to the viewer. When another pixel is drawn at the same location the z
// values are compared in order to determine which pixel should be drawn.
gl.enable(gl.DEPTH_TEST);
// Specify which function to use for depth buffer comparisons. It compares the
// value of the incoming pixel against the one stored in the depth buffer.
// Possible values are (from the OpenGL documentation):
// GL_NEVER - Never passes.
// GL_LESS - Passes if the incoming depth value is less than the stored depth value.
// GL_EQUAL - Passes if the incoming depth value is equal to the stored depth value.
// GL_LEQUAL - Passes if the incoming depth value is less than or equal to the stored depth value.
// GL_GREATER - Passes if the incoming depth value is greater than the stored depth value.
// GL_NOTEQUAL - Passes if the incoming depth value is not equal to the stored depth value.
// GL_GEQUAL - Passes if the incoming depth value is greater than or equal to the stored depth value.
// GL_ALWAYS - Always passes.
gl.depthFunc(gl.LEQUAL);

// Now create a shape.
// First create a vertex buffer in which we can store our data.
var vertexBuffer = gl.createBuffer();
// Bind the buffer object to the ARRAY_BUFFER target.
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
// Specify the vertex positions (x, y, z)
var vertices = new Float32Array([
0.0, 1.0, 4.0,
-1.0, -1.0, 4.0,
1.0, -1.0, 4.0
]);

// Creates a new data store for the vertices array which is bound to the ARRAY_BUFFER.
// The third paramater indicates the usage pattern of the data store. Possible values are
// (from the OpenGL documentation):
// The frequency of access may be one of these:
// STREAM - The data store contents will be modified once and used at most a few times.
// STATIC - The data store contents will be modified once and used many times.
// DYNAMIC - The data store contents will be modified repeatedly and used many times.
// The nature of access may be one of these:
// DRAW - The data store contents are modified by the application, and used as the source for
// GL drawing and image specification commands.
// READ - The data store contents are modified by reading data from the GL, and used to return
// that data when queried by the application.
// COPY - The data store contents are modified by reading data from the GL, and used as the source
// for GL drawing and image specification commands.
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

// Clear the color buffer and the depth buffer
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);


// Define the viewing frustum parameters
// More info: http://en.wikipedia.org/wiki/Viewing_frustum
// More info: http://knol.google.com/k/view-frustum
var fieldOfView = 30.0;
var aspectRatio = canvas.width / canvas.height;
var nearPlane = 1.0;
var farPlane = 10000.0;
var top = nearPlane * Math.tan(fieldOfView * Math.PI / 360.0);
var bottom = -top;
var right = top * aspectRatio;
var left = -right;


// Create the perspective matrix. The OpenGL function that's normally used for this,
// glFrustum() is not included in the WebGL API. That's why we have to do it manually here.
// More info: http://www.cs.utk.edu/~vose/c-stuff/opengl/glFrustum.html
var a = (right + left) / (right - left);
var b = (top + bottom) / (top - bottom);
var c = (farPlane + nearPlane) / (farPlane - nearPlane);
var d = (2 * farPlane * nearPlane) / (farPlane - nearPlane);
var x = (2 * nearPlane) / (right - left);
var y = (2 * nearPlane) / (top - bottom);
var perspectiveMatrix = [
x, 0, a, 0,
0, y, b, 0,
0, 0, c, d,
0, 0, -1, 0
];

// Create the modelview matrix
// More info about the modelview matrix: http://3dengine.org/Modelview_matrix
// More info about the identity matrix: http://en.wikipedia.org/wiki/Identity_matrix
var modelViewMatrix = [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
];
// Get the vertex position attribute location from the shader program
var vertexPosAttribLocation = gl.getAttribLocation(gl.program, "vertexPosition");
// Specify the location and format of the vertex position attribute
gl.vertexAttribPointer(vertexPosAttribLocation, 3.0, gl.FLOAT, false, 0, 0);
// Get the location of the "modelViewMatrix" uniform variable from the
// shader program
var uModelViewMatrix = gl.getUniformLocation(gl.program, "modelViewMatrix");
// Get the location of the "perspectiveMatrix" uniform variable from the
// shader program
var uPerspectiveMatrix = gl.getUniformLocation(gl.program, "perspectiveMatrix");
// Set the values
gl.uniformMatrix4fv(uModelViewMatrix, false, new Float32Array(perspectiveMatrix));
gl.uniformMatrix4fv(uPerspectiveMatrix, false, new Float32Array(modelViewMatrix));
// Draw the triangles in the vertex buffer. The first parameter specifies what
// drawing mode to use. This can be POINTS, LINE_STRIP, LINE_LOOP, LINES, TRIANGLE_STRIP,
// TRIANGLE_FAN and TRIANGLES
gl.drawArrays(gl.TRIANGLES, 0, vertices.length / 3.0);
gl.flush();
}
</script>

  • Delicious
  • Facebook
  • Digg
  • Reddit
  • StumbleUpon
  • Twitter

17 thoughts on “Beginning WebGL step-by-step tutorial

  1. Lukas says:

    Hi I just have a question. I did OpenGL years ago. What I see now you are using shaders etc to render even primitive objects. I m used to use a gl_begin and draw_list…

    Is it still possible to use it or only shaders are supported now (in webgl)?

  2. A great intro, but there’s a couple of bugs in your implementation.

    – When failing to link the program, you’re deleting the shaders with a call to deleteProgram.

    – When setting the perspective and modelView matrices you’ve mixed them up:
    gl.uniformMatrix4fv(uModelViewMatrix, false,
    new Float32Array(perspectiveMatrix));
    gl.uniformMatrix4fv(uPerspectiveMatrix, false,
    new Float32Array(modelViewMatrix));

    should be:
    gl.uniformMatrix4fv(uModelViewMatrix, false,
    new Float32Array(modelViewMatrix));
    gl.uniformMatrix4fv(uPerspectiveMatrix, false,
    new Float32Array(perspectiveMatrix));

  3. Thanks, this is a really great tutorial. Nice to see how it’s done without extra js libraries.

    One small thing… I’m still a newbie to this, so correct me if I’m wrong, but I think on lines 225 and 226 of your code, the use of the perspectiveMatrix and modelViewMatrix variables are swapped. I think that what you have as…

    gl.uniformMatrix4fv(uModelViewMatrix, false, new Float32Array(perspectiveMatrix));
    gl.uniformMatrix4fv(uPerspectiveMatrix, false, new Float32Array(modelViewMatrix));

    … should be …

    gl.uniformMatrix4fv(uModelViewMatrix, false, new Float32Array(modelViewMatrix));
    gl.uniformMatrix4fv(uPerspectiveMatrix, false, new Float32Array(perspectiveMatrix));

    … maybe it works anyway, in the example, because the modelview is the identity transformation. When I started playing around with the modelview, I think this correction made things work a little better.

  4. Philip Schlup says:

    Thank you for posting this. I’m not a big fan of external libraries, so it’s great that you’ve written it without dependencies.

  5. @BabyRaptor: … and thank you for your constructive criticism. I create tutorials and I build free, open source frameworks exactly for this kind of glorious recognition.

    I tested this on Chrome & Firefox and on Mac OS & Windows. Next time tell me what platform & browser you’re working on and what error you get before calling it a pile of crap.

  6. SoHotCall says:

    Wow, needs so many lines of code just to draw a triangle..
    Nice tutorial, anyway.
    Next tutorial should be adding image texture to the triangle,
    and then making simple animation..

    @BabyRaptor: The code that is displayed here is not the complete code.
    It is just the part, and you will need to add the etc.
    The [complete] source file for this tutorial can be found at http://www.rozengain.com/files/webgl/tutorial/WebGLTutorial.html

  7. Curious says:

    Interesting !
    But as a simple user of javascript I don’t understand the goal of most of the code.
    Maybe if there was another example I would get a better understanding by comparing both sources…

  8. Recently a series of WebGL gamedev tutorials have been published covering game logic, content optimization, level design and Android/iOS mobile browsers support.

    There are currently 4 tutorials which can be accessed by the link.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>