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
Real-Time 3D Graphics with WebGL 2

You're reading from   Real-Time 3D Graphics with WebGL 2 Build interactive 3D applications with JavaScript and WebGL 2 (OpenGL ES 3.0)

Arrow left icon
Product type Paperback
Published in Oct 2018
Publisher Packt
ISBN-13 9781788629690
Length 500 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Farhad Ghayour Farhad Ghayour
Author Profile Icon Farhad Ghayour
Farhad Ghayour
Diego Cantor Diego Cantor
Author Profile Icon Diego Cantor
Diego Cantor
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Getting Started FREE CHAPTER 2. Rendering 3. Lights 4. Cameras 5. Animations 6. Colors, Depth Testing, and Alpha Blending 7. Textures 8. Picking 9. Putting It All Together 10. Advanced Techniques 11. WebGL 2 Highlights 12. Journey Ahead 13. Other Books You May Enjoy

Time for Action: Setting up WebGL Context Attributes

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

  1. Using your favorite text editor, open the ch01_03_attributes.html file:
<html>
<head>
<title>Real-Time 3D Graphics with WebGL2</title>
<link rel="shortcut icon" type="image/png"
href="/common/images/favicon.png" />

<style>
canvas {
border: 5px dotted blue;
}
</style>

<script type="text/javascript">
'use strict';

let gl;

function updateClearColor(...color) {
// The ES6 spread operator (...) allows for us to
// use elements of an array as arguments to a function
gl.clearColor(...color);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.viewport(0, 0, 0, 0);
}

function checkKey(event) {
switch (event.keyCode) {
// number 1 => green
case 49: {
updateClearColor(0.2, 0.8, 0.2, 1.0);
break;
}
// number 2 => blue
case 50: {
updateClearColor(0.2, 0.2, 0.8, 1.0);
break;
}
// number 3 => random color
case 51: {
updateClearColor(Math.random(), Math.random(),
Math.random(), 1.0);
break;
}
// number 4 => get color
case 52: {
const color = gl.getParameter(gl.COLOR_CLEAR_VALUE);
// Don't let the following line confuse you.
// It basically rounds up the numbers to one
// decimal cipher for visualization purposes.

// TIP: Given that WebGL's color space ranges
// from 0 to 1 you can multiply these values by 255
// to display in their RGB values.
alert(`clearColor = (
${color[0].toFixed(1)},
${color[1].toFixed(1)},
${color[2].toFixed(1)}
)`);
window.focus();
break;
}
}
}

function init() {
const canvas = document.getElementById('webgl-canvas');

if (!canvas) {
console.error('Sorry! No HTML5 Canvas was found on this page');
return;
}

gl = canvas.getContext('webgl2');

const message = gl
? 'Hooray! You got a WebGL2 context'
: 'Sorry! WebGL is not available';

alert(message);

// Call checkKey whenever a key is pressed
window.onkeydown = checkKey;
}

window.onload = init;
</script>
</head>
<body>

<canvas id="webgl-canvas" width="800" height="600">
Your browser does not support the HTML5 canvas element.
</canvas>

</body>
</html>
  1. You will see that this file is similar to our previous example. However, there are new code constructs that we will explain briefly. This file contains three JavaScript functions:
Function Description
updateClearColor Updates clearColor and then sets the canvas element clear color, which is one of the WebGL context attributes. As previously mentioned, WebGL works as a state machine. Therefore, it will maintain this color until it's changed using the gl.clearColor WebGL function (see the checkKey source code).
checkKey This is an auxiliary function that has been attached to the window onkeydown event. It captures the keyboard input and executes code depending on the key entered.
init This function gets called on the document onload event. It obtains a WebGL context and sets it to the global gl variable.
  1. Open the ch01_03_attributes.html file in your browser.
  1. Press 1. You will see how the canvas changes its color to green. If you want to query the exact color used, press 4.
  2. The canvas element will maintain the green color until we change it 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 4.
  3. You can press 3 to set the clear color to a random color. As before, you can get the color by pressing 4:

What just happened?

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

Throughout this book, we will encounter similar constructs where specific functions establish attributes of the WebGL context while 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 essential to note 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 API will be performed using this variable.

You have been reading a chapter from
Real-Time 3D Graphics with WebGL 2 - Second Edition
Published in: Oct 2018
Publisher: Packt
ISBN-13: 9781788629690
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 AU $24.99/month. Cancel anytime