WebGL : Starter Kit for Drawing

I was searching for a good tutorial on WebGL and found this one, WebGL Basics quite interesting. First two or three pages of this explains the architecture of WebGL and how it works. It really helps you to understand the coordinate system, vertices, indices, arrays, buffers, shaders etc. in WebGL. After that there is a sample application which demonstrates how Javascript code can be written to draw on canvas using WebGL context. It helped me a lot and I was able to experiment with it. To reuse the code for creating different examples, I modified the code and rewrote it in ES6.

The sequence of WebGL program is given below

  1. Get WebGL context
  2. Create geometric data and buffer objects
  3. Define and link Shaders
  4. Create and enable Attributes, associate shaders with buffer
  5. Set up and clear WegGL context
  6. Draw using WebGL context

In this starter kit, I have created functions for each step and you can easily play around with shaders and the drawing function to do experiments with WebGL. This project is written in ES6 and uses Babel Standalone as client-side transcompiler.

This draws a simple rectangle with its vertices highlighted.


Output






Download the project

What to do

  1. Edit start function to change vertices array
  2. Edit shader script-tag code to modify shaders
  3. Edit draw function to change the way it is drawn
  4. Experiment with drawing

The project has three source files

  1. index.html
  2. main.js
  3. main.css

index.html

This does the following

  1. Loads
    • babel
    • main.js
    • main.css
  2. Holds the canvas tag
  3. Holds the script tag for
    • Vertex Shader
    • Fragment Shader

In the head it has


and in the body


main.js


This has an ES6 module named WebGLStarterKit and executes the program in the sequence described above. The entry point function is start. The steps in the sequence can be roughly mapped to the functions as shown below

  1. Get WebGL context : constructor
  2. Create geometric data and buffer objects : start, createVertexBuffer
  3. Define and link Shaders : createShaderProgram
  4. Create and enable Attributes, associate shaders with buffer : setShaderBuffer
  5. Set up and clear WegGL context : setStage
  6. Draw using WebGL context : draw



main.css


Simple css file with a border style

I have created many examples reusing this project. I will be sharing them soon.

Share