Book Image

WebGL Beginner's Guide

Book Image

WebGL Beginner's Guide

Overview of this book

WebGL is a new web technology that brings hardware-accelerated 3D graphics to the browser without installing additional software. As WebGL is based on OpenGL and brings in a new concept of 3D graphics programming to web development, it may seem unfamiliar to even experienced Web developers.Packed with many examples, this book shows how WebGL can be easy to learn despite its unfriendly appearance. Each chapter addresses one of the important aspects of 3D graphics programming and presents different alternatives for its implementation. The topics are always associated with exercises that will allow the reader to put the concepts to the test in an immediate manner.WebGL Beginner's Guide presents a clear road map to learning WebGL. Each chapter starts with a summary of the learning goals for the chapter, followed by a detailed description of each topic. The book offers example-rich, up-to-date introductions to a wide range of essential WebGL topics, including drawing, color, texture, transformations, framebuffers, light, surfaces, geometry, and more. With each chapter, you will "level up"ù your 3D graphics programming skills. This book will become your trustworthy companion filled with the information required to develop cool-looking 3D web applications with WebGL and JavaScript.
Table of Contents (18 chapters)
WebGL Beginner's Guide
Credits
About the Authors
Acknowledgement
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – setting up WebGL context attributes


In this example, we are going to learn to modify the color that we use to clear the canvas:

  1. Using your favorite text editor, open the file ch1_GL_Attributes.html:

    <html>
    <head>
       <title> WebGL Beginner's Guide - Setting WebGL context attributes </title>
        <style type="text/css">
       canvas {border: 2px dotted blue;}
       </style>
       
       <script>
        var gl = null;
        var c_width = 0;
        var c_height = 0;
        
        window.onkeydown = checkKey;
        
        function checkKey(ev){
          switch(ev.keyCode){
          case 49:{ // 1
               gl.clearColor(0.3,0.7,0.2,1.0);
            clear(gl);
            break;
          }
          case 50:{ // 2
            gl.clearColor(0.3,0.2,0.7,1.0);
            clear(gl);
            break;
          }
          case 51:{ // 3
            var color = gl.getParameter(gl.COLOR_CLEAR_VALUE);
            
            // Don't get confused with the following line. It 
                 // basically rounds up the numbers to one decimalcipher    
                 //just for visualization purposes
            alert('clearColor = (' + 
                          Math.round(color[0]*10)/10 + 
                    ',' + Math.round(color[1]*10)/10+
                    ',' + Math.round(color[2]*10)/10+')');
            
                 window.focus();
            break;
          }
          }
        }
        
        function getGLContext(){
          var canvas = document.getElementById("canvas-element-id");
          if (canvas == null){
              alert("there is no canvas on this page");
              return;
          }
    
          var names = ["webgl", 
                       "experimental-webgl", 
                       "webkit-3d", 
                       "moz-webgl"];
           var ctx = null;
           for (var i = 0; i < names.length; ++i) {
               try {
                   ctx = canvas.getContext(names[i]);
               } 
               catch(e) {}
               if (ctx) break;
           }
    
           if (ctx == null){
             alert("WebGL is not available");
              }
           else{
              return ctx;
           }
       }      
          
    
        
        function clear(ctx){
          ctx.clear(ctx.COLOR_BUFFER_BIT);               
              ctx.viewport(0, 0, c_width, c_height);
        }
        
        function initWebGL(){
          gl = getGLContext();
          
        }
       </script>
    </head>
    
    <body onLoad="initWebGL()">
        <canvas id="canvas-element-id" width="800" height="600">
            Your browser does not support the HTML5 canvas element.
        </canvas>
    </body>
    
    </html>
  2. You will see that this file is very similar to our previous example. However, there are new code constructs that we will explain briefly. This file contains four JavaScript functions:

    Function

    Description

    checkKey

    This is an auxiliary function. It captures the keyboard input and executes code depending on the key entered.

    getGLContext

    Similar to the one used in the Time for action – accessing the WebGL context section. In this version, we are adding some lines of code to obtain the canvas' width and height.

    clear

    Clear the canvas to the current clear color, which is one attribute of the WebGL context. As was mentioned previously, WebGL works as a state machine, therefore it will maintain the selected color to clear the canvas up to when this color is changed using the WebGL function gl.clearColor (See the checkKey source code)

    initWebGL

    This function replaces getGLContext as the function being called on the document onLoad event. This function calls an improved version of getGLContext that returns the context in the ctx variable. This context is then assigned to the global variable gl.

  3. Open the file test_gl_attributes.html using one of the supported Internet web browsers.

  4. Press 1. You will see how the canvas changes its color to green. If you want to query the exact color we used, press 3.

  5. The canvas will maintain the green color until we decided to change the attribute clear color by calling gl.clearColor. Let's change it by pressing 2. If you look at the source code, this will change the canvas clear color to blue. If you want to know the exact color, press 3.

What just happened?

In this example, we saw that we can change or set the color that WebGL uses to clear the canvas by calling the clearColor function. Correspondingly, we used getParameter(gl.COLOR_CLEAR_VALUE) to obtain the current value for the canvas clear color.

Throughout the book we will see similar constructs where specific functions establish attributes of the WebGL context and the getParameter function retrieves the current values for such attributes whenever the respective argument (in our example, COLOR_CLEAR_VALUE) is used.

Using the context to access the WebGL API

It is also essential to note here that all of the WebGL functions are accessed through the WebGL context. In our examples, the context is being held by the gl variable. Therefore, any call to the WebGL Application Programming Interface (API) will be performed using this variable.