Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
WebGL Beginner's Guide

You're reading from   WebGL Beginner's Guide If you're a JavaScript developer who wants to take the plunge into 3D web development, this is the perfect primer. From a basic understanding of WebGL structure to creating realistic 3D scenes, everything you need is here.

Arrow left icon
Product type Paperback
Published in Jun 2012
Publisher Packt
ISBN-13 9781849691727
Length 376 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Toc

Table of Contents (18) Chapters Close

WebGL Beginner's Guide
Credits
About the Authors
Acknowledgement
About the Reviewers
www.PacktPub.com
Preface
1. Getting Started with WebGL FREE CHAPTER 2. Rendering Geometry 3. Lights! 4. Camera 5. Action 6. Colors, Depth Testing, and Alpha Blending 7. Textures 8. Picking 9. Putting It All Together 10. Advanced Techniques 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.

You have been reading a chapter from
WebGL Beginner's Guide
Published in: Jun 2012
Publisher: Packt
ISBN-13: 9781849691727
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime