Book Image

Real-Time 3D Graphics with WebGL 2 - Second Edition

By : Farhad Ghayour, Diego Cantor
5 (1)
Book Image

Real-Time 3D Graphics with WebGL 2 - Second Edition

5 (1)
By: Farhad Ghayour, Diego Cantor

Overview of this book

As highly interactive applications have become an increasingly important part of the user experience, WebGL is a unique and cutting-edge technology that brings hardware-accelerated 3D graphics to the web. Packed with 80+ examples, this book guides readers through the landscape of real-time computer graphics using WebGL 2. Each chapter covers foundational concepts in 3D graphics programming with various implementations. Topics are always associated with exercises for a hands-on approach to learning. This book presents a clear roadmap to learning real-time 3D computer graphics with WebGL 2. 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 3D computer graphics topics, including rendering, colors, textures, transformations, framebuffers, lights, surfaces, blending, geometry construction, advanced techniques, and more. With each chapter, you will "level up" your 3D graphics programming skills. This book will become your trustworthy companion in developing highly interactive 3D web applications with WebGL and JavaScript.
Table of Contents (14 chapters)

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.