User Tools

Site Tools


Sidebar

General

Python Tutorials

WebGL Tutorials

Node.js Tutorials

Node.js in WebStorm


Martin Christen

View Martin Christen's profile on LinkedIn


Twitter

Timeline of @MartinChristen

MartinChristen avatar

RT @TFConsult: Celebrating 100th birthday of #physicist #RichardFeynman: The marvellous #Feynman lectures on #physics: https://t.co/81as7mN
About 1 week, 4 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @sergerey: Had a fantastic time giving our workshop on Spatial Data Science with PyData at @GeoPythonConf with @levijohnwolf. Looking f…
About 1 week, 5 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @fridex: Everything has an end even such an excellent conference #GeoPythonConf in Basel. Thanks to organizers for such an outstanding c…
About 1 week, 5 days ago by: Martin Christen (@MartinChristen)
webgl:tutorial01

WebGL Tutorial 1: Creating a WebGL Canvas

First we need to create a HTML5 index.html. In Line 3,4 and 5 the function “init” is added which will be extended to initialize the WebGL rendering context.

<html>
    <head>
        <script type="text/javascript">
           function init() {}
        </script> 
    </head>
    <body onload="init()">
        <div style="text-align: center">
            <canvas id="canvas" width="640" height="480"></canvas>
        </div>
    </body>
</html>

The code to initlize the WebGL context would look like this:

   function init() {
   var canvas = document.getElementById("canvas");
   var gl = canvas.getContext("webgl") || 
            canvas.getContext("experimental-webgl");
   }

To retrieve the WebGLRenderingContext some browsers still need “experimental-webgl” instead of “webgl”, therefore we try both. In future “experimental-webgl” shouldn't be used anymore.

if the gl variable is not null we have a valid WebGL rendering context.

Now you can add some clear color and clear the canvas with a color:

gl.clearColor(1, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

Of course it is nicer if we try to catch errors when setting up WebGL. A function “initWebGL()” to initialize WebGL is created here, which returns the WebGLRenderingContext or null if there is a problem.

function initWebGL(canvas) {
   var gl = null;
  
   try {
      gl = canvas.getContext("webgl") || 
           canvas.getContext("experimental-webgl");
   }
   catch(e) { 
      gl = null;
   }
  
   return gl;
}


webgl/tutorial01.txt · Last modified: 2013/09/07 21:48 by mchristen