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 @snebiker: #PlayGameLieschtel - brilliant event by Kantonsbibliothek Baselland #KBL to get kids into libraries, including family #gamede…
About 2 days, 13 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

Only a handful tickets left for @PyConDE in Karlsruhe (October 24-28, 2018) - The schedule is now available at… https://t.co/Og4fp3DsoA
About 5 days, 6 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

IAMCP & @swissmade_sw Augmented Reality event just started https://t.co/bdREI6lJM4 #ar #AugmentedReality #Basel… https://t.co/9KpsdU3fvM
About 6 days, 12 hours 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