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

On my way to the 3D city model workshop in Bonn where I‘m presenting our latest @igeoFHNW #AugmentedReality App… https://t.co/8ghq4GfZW5
About 5 days, 6 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

Teaching #Python to 11-13-year-old girls was great fun today at the Swiss national future day (#zukunftstag).… https://t.co/1lDmWdl02D
About 1 week, 2 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @GeoPythonConf: Interested in joining GeoPython 2019? Register to the mailing list: https://t.co/ub3CU7L5WL #python #GeoPython #geospat…
About 2 weeks, 2 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