Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
WebGL Beginner's Guide
WebGL Beginner's Guide

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.

eBook
€19.99 €28.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

WebGL Beginner's Guide

Chapter 2. Rendering Geometry

WebGL renders objects following a "divide and conquer" approach. Complex polygons are decomposed into triangles, lines, and point primitives. Then, each geometric primitive is processed in parallel by the GPU through a series of steps, known as the rendering pipeline, in order to create the final scene that is displayed on the canvas.

The first step to use the rendering pipeline is to define geometric entities. In this chapter, we will take a look at how geometric entities are defined in WebGL.

In this chapter, we will:

  • Understand how WebGL defines and processes geometric information

  • Discuss the relevant API methods that relate to geometry manipulation

  • Examine why and how to use JavaScript Object Notation (JSON) to define, store, and load complex geometries

  • Continue our analysis of WebGL as a state machine and describe the attributes relevant to geometry manipulation that can be set and retrieved from the state machine

  • Experiment with creating and loading different...

Vertices and Indices


WebGL handles geometry in a standard way, independently of the complexity and number of points that surfaces can have. There are two data types that are fundamental to represent the geometry of any 3D object: vertices and indices.

Vertices are the points that define the corners of 3D objects. Each vertex is represented by three floating-point numbers that correspond to the x, y, and z coordinates of the vertex. Unlike its cousin, OpenGL, WebGL does not provide API methods to pass independent vertices to the rendering pipeline, therefore we need to write all of our vertices in a JavaScript array and then construct a WebGL vertex buffer with it.

Indices are numeric labels for the vertices in a given 3D scene. Indices allow us to tell WebGL how to connect vertices in order to produce a surface. Just like with vertices, indices are stored in a JavaScript array and then they are passed along to WebGL's rendering pipeline using a WebGL index buffer.

Note

There are two kind...

Overview of WebGL's rendering pipeline


Here we will see a simplified version of WebGL's rendering pipeline. In subsequent chapters, we will discuss the pipeline in more detail.

Let's take a moment to describe every element separately.

Vertex Buffer Objects (VBOs)

VBOs contain the data that WebGL requires to describe the geometry that is going to be rendered. As mentioned in the introduction, vertex coordinates are usually stored and processed in WebGL as VBOs. Additionally, there are several data elements such as vertex normals, colors, and texture coordinates, among others, that can be modeled as VBOs.

Vertex shader

The vertex shader is called on each vertex. This shader manipulates per-vertex data such as vertex coordinates, normals, colors, and texture coordinates. This data is represented by attributes inside the vertex shader. Each attribute points to a VBO from where it reads vertex data.

Fragment shader

Every set of three vertices defines a triangle and each element on the surface of that...

Rendering geometry in WebGL


The following are the steps that we will follow in this section to render an object in WebGL:

  1. First, we will define a geometry using JavaScript arrays.

  2. Second, we will create the respective WebGL buffers.

  3. Third, we will point a vertex shader attribute to the VBO that we created in the previous step to store vertex coordinates.

  4. Finally, we will use the IBO to perform the rendering.

Defining a geometry using JavaScript arrays

Let's see what we need to do to create a trapezoid. We need two JavaScript arrays: one for the vertices and one for the indices.

As you can see from the previous screenshot, we have placed the coordinates sequentially in the vertex array and then we have indicated in the index array how these coordinates are used to draw the trapezoid. So, the first triangle is formed with the vertices having indices 0, 1, and 2; the second with the vertices having indices 1, 2, and 3; and finally, the third, with vertices having indices 2, 3, and 4. We will follow...

Putting everything together


I guess you have been waiting to see how everything works together. Let's start with some code. Let's create a simple WebGL program to render a square.

Time for action – rendering a square


Follow the given steps:

  1. Open the file ch_Square.html in your favorite HTML editor (ideally one that supports syntax highlighting like Notepad++ or Crimson Editor).

  2. Let's examine the structure of this file with the help of the following diagram:

  3. The web page contains the following:

    • The script <script id="shader-fs" type="x-shader/x-fragment"> contains the fragment shader code.

    • The script <script id="shader-vs" type="x-shader/x-vertex"> contains the vertex shader code. We will not be paying attention to these two scripts as these will be the main point of study in the next chapter. For now, let's notice that we have a fragment shader and a vertex shader.

    • The next script on our web page <script id="code-js" type="text/javascript"> contains all the JavaScript WebGL code that we will need. This script is divided into the following functions:

    • getGLContext : Similar to the function that we saw in the previous chapter, this function allows us to get...

Rendering modes


Let's revisit the signature of the drawElements function:

gl.drawElements(Mode, Count, Type, Offset)

The first parameter determines the type of primitives that we are rendering. In the following time for action section, we are going to see with examples the different rendering modes.

Time for action – rendering modes


Follow the given steps:

  1. Open the file ch_RenderingModes.html in the HTML5 browser of your preference. This example follows the same structure as discussed in the previous section.

  2. Select the WebGL JS button and scroll down to the initBuffer function.

  3. You will see here that we are drawing a trapezoid. However, on screen you will see two triangles! We will see how we did this later.

  4. At the bottom of the page, there is a combobox that allows you to select the different rendering modes that WebGL provides, as shown in the following screenshot:

  5. When you select any option from this combobox, you are changing the value of the renderingMode variable defined at the top of the WebGL JS code (scroll up if you want to see where it is defined).

  6. To see how each option modifies the rendering, scroll down to the drawScene function.

  7. You will see there that after binding the IBO trapezoidIndexBuffer with the following instruction:

    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, trapezoidIndexBuffer...

WebGL as a state machine: buffer manipulation


There is some information about the state of the rendering pipeline that we can retrieve when we are dealing with buffers with the functions: getParameter, getBufferParameter, and isBuffer.

Just like we did in the previous chapter, we will use getParameter(parameter) where parameter can have the following values:

  • ARRAY_BUFFER_BINDING: It retrieves a reference to the currently-bound VBO

  • ELEMENT_ARRAY_BUFFER_BINDING: It retrieves a reference to the currently-bound IBO

Also, we can enquire about the size and the usage of the currently-bound VBO and IBO using getBufferParameter(type, parameter) where type can have the following values:

  • ARRAY_BUFFER: To refer to the currently bound VBO

  • ELEMENT_ARRAY_BUFFER: To refer to the currently bound IBO

And parameter can be:

  • BUFFER_SIZE: Returns the size of the requested buffer

  • BUFFER_USAGE: Returns the usage of the requested buffer

Note

Your VBO and/or IBO needs to be bound when you enquire about the state of...

Time for action – enquiring on the state of buffers


Follow the given steps:

  1. Open the file ch2_StateMachine.html in the HTML5 browser of your preference.

  2. Scroll down to the initBuffers method. You will see something similar to the following screenshot:

  3. Pay attention to how we use the methods discussed in this section to retrieve and display information about the current state of the buffers.

  4. The information queried by the initBuffer function is shown at the bottom portion of the web page using updateInfo (if you look closely at runWebGLApp code you will see that updateInfo is called right after calling initBuffers).

  5. At the bottom of the web page (scroll down the web page if necessary), you will see the following result:

  6. Now, open the same file (ch2_StateMachine.html) in a text editor.

  7. Cut the line:

    gl.bindBuffer(gl.ARRAY_BUFFER,null);

    and paste it right before the line:

    coneIndexBuffer = gl.createBuffer();
  8. What happens when you launch the page in your browser again?

  9. Why do you think this behavior occurs...

Advanced geometry loading techniques: JavaScript Object Notation (JSON) and AJAX


So far, we have rendered very simple objects. Now let's study a way to load the geometry (vertices and indices) from a file instead of declaring the vertices and the indices every time we call initBuffers. To achieve this, we will make asynchronous calls to the web server using AJAX. We will retrieve the file with our geometry from the web server and then we will use the built-in JSON parser to convert the context of our files into JavaScript objects. In our case, these objects will be the vertices and indices array.

Introduction to JSON – JavaScript Object Notation

JSON stands for JavaScript Object Notation. It is a lightweight, text-based, open format used for data interchange. JSON is commonly used as an alternative to XML.

The JSON format is language-agnostic. This means that there are parsers in many languages to read and interpret JSON objects. Also, JSON is a subset of the object literal notation of JavaScript...

Time for action – JSON encoding and decoding


Let's create a simple model: a 3D line. Here we will be focusing on how we do JSON encoding and decoding. Follow the given steps:

  1. Go to your Internet browser and open the interactive JavaScript console. Use the following table for assistance:

    Web browser

    Menu option

    Shortcut keys (PC / Mac)

    Firefox

    Tools | Web Developer | Web Console

    Ctrl + Shift + K / Command + Alt + K

    Safari

    Develop | Show Web Inspector

    Ctrl + Shift + C / Command + Alt + C

    Chrome

    Tools | JavaScript Console

    Ctrl + Shift + J / Command + Alt + J

  2. Create a JSON object by typing:

    var model = {"vertices":[0,0,0,1,1,1], "indices":[0,1]};
  3. Verify that the model is an object by writing:

    typeof(model)
  4. Now, let's print the model attributes. Write this in the console (press Enter at the end of each line):

    model.vertices
    model.indices
  5. Now, let's create a JSON text:

    var text = JSON.stringify(model)
    alert(text)
  6. What happens when you type text.vertices?

    As you can see, you get an...

Time for action – loading a cone with AJAX + JSON


Follow the given steps:

  1. Make sure that your web server is running and access the file ch2_AJAXJSON.html using your web server.

    Note

    You know you are using the web server if the URL in the address bar starts with localhost/… instead of file://...

  2. The folder where you have the code for this chapter should look like this:

  3. Click on ch2_AjaxJSON.html.

  4. The example will load in your browser and you will see something similar to this:

  5. When you click on the JavaScript alert, you will see:

  6. As the page says, please review the functions loadModel and handleLoadedModel to better understand the use of AJAX and JSON in the application.

  7. What does the modelLoaded variable do? (check the source code).

  8. See what happens when you change the color in the file models/cone.json and reload the page.

  9. Modify the coordinates of the cone in the file models/cone.json and reload the page. Here you can verify that WebGL reads and renders the coordinates from the file. If you modify...

Summary


In this chapter, we have discussed how WebGL renders geometry. Remember that there are two kinds of WebGL buffers that deal with geometry rendering: VBOs and IBOs.

WebGL's rendering pipeline describes how the WebGL buffers are used and passed in the form of attributes to be processed by the vertex shader. The vertex shader parallelizes vertex processing in the GPU. Vertices define the surface of the geometry that is going to be rendered. Every element on this surface is known as a fragment. These fragments are processed by the fragment shader. Fragment processing also occurs in parallel in the GPU. When all the fragments have been processed, the framebuffer, a two-dimensional array, contains the image that is then displayed on your screen.

WebGL works as a state machine. As such, properties referring to buffers are available and their values will be dependent on the buffer currently bound.

We also saw that JSON and AJAX are two JavaScript technologies that integrate really well with...

Left arrow icon Right arrow icon

Key benefits

  • Dive headfirst into 3D web application development using WebGL and JavaScript.
  • Each chapter is loaded with code examples and exercises that allow the reader to quickly learn the various concepts associated with 3D web development
  • The only software that the reader needs to run the examples is an HTML5 enabled modern web browser. No additional tools needed.
  • A practical beginner's guide with a fast paced but friendly and engaging approach towards 3D web development

Description

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.

Who is this book for?

This book is written for JavaScript developers who are interested in 3D web development. A basic understanding of the DOM object model and the jQuery library is ideal but not required. No prior WebGL knowledge is expected.

What you will learn

  • Understand the structure of a WebGL application
  • Build and render 3D objects with WebGL
  • Load complex models using JSON and AJAX
  • Set up a lighting model using shaders, physics of light reflection, and lighting strategies
  • Create a camera and use it to move around a 3D scene
  • Use texturing, lighting and shading techniques to add greater realism to 3D scenes
  • Implement selection of objects in a 3D scene with the mouse
  • Advanced techniques to create more visually complex and compelling scenes

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 15, 2012
Length: 376 pages
Edition : 1st
Language : English
ISBN-13 : 9781849691734
Vendor :
Khronos Group
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jun 15, 2012
Length: 376 pages
Edition : 1st
Language : English
ISBN-13 : 9781849691734
Vendor :
Khronos Group
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 112.97
Responsive Web Design with HTML5 and CSS3
€32.99
WebGL Beginner's Guide
€37.99
OpenGL Development Cookbook
€41.99
Total 112.97 Stars icon
Banner background image

Table of Contents

10 Chapters
Getting Started with WebGL Chevron down icon Chevron up icon
Rendering Geometry Chevron down icon Chevron up icon
Lights! Chevron down icon Chevron up icon
Camera Chevron down icon Chevron up icon
Action Chevron down icon Chevron up icon
Colors, Depth Testing, and Alpha Blending Chevron down icon Chevron up icon
Textures Chevron down icon Chevron up icon
Picking Chevron down icon Chevron up icon
Putting It All Together Chevron down icon Chevron up icon
Advanced Techniques Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(9 Ratings)
5 star 44.4%
4 star 33.3%
3 star 22.2%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Keith Hoffman Nov 15, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
"Awesome, Thanks!"
Amazon Verified review Amazon
Bernardo Apr 26, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
El tema de WebGL resulta algo complicado por la cantidad de conceptos que maneja. Pues bien, en este libro se combina una excelente pedagogía con ejemplos prácticos muy bien elaborados que facilmente se pueden implementar en un servidor web. No hay nada prescindible en este libro, todos los capítulos son esenciales. Merece la pena pagar lo que vale, es una buena inversión. Si te gusta el tema de WebGL disfrutarás con este libro y si eres un neófito como yo acabarás enganchado.
Amazon Verified review Amazon
C. Moeller Oct 01, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you have wanted to start learning any kind of OpenGL, WebGL is a great way to start learning. This book provides a lot of information about using WebGL, from just introducing the canvas tag, to actually loading models from Blender in obj format, picking geometry using the mouse and ray tracing, and even using shaders in your WebGL application.If you have used OpenGL or OpenGL ES before, a lot of the techniques will be very familiar. If you haven't he starts off at the beginning, explaining everything thoroughly, and as long as you have programmed before, and hopefully have used Javascript, you will be able to start creating WebGL apps using modern techniques. The advantages of using WebGL include not needing to compile anything, so any text editor is all you really need(although I would recomend at least using notepad++), it uses Javascript, so has a relatively low barrier of entry for more novice programmers, and it's viewable on the web- so you could upload it to your website for everyone to be able to check out.If you know some Javascript, and are interested in adding anywhere from simple 3d, up to enough to create a small 3d game, this book would be able to get you started, and confident with using WebGL.
Amazon Verified review Amazon
marketminutdave Sep 16, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is soo good but admittedly I've only read One and a half chapters. Very easy to understand and even MOre intuitive than the JavaScript book I reviewed; here's a section:Buffers that contain vertex data are known as Vertex Buffer Objects ( VBOs ). Similarly, buffers that contain index data are known as Index Buffer Objects ( IBOs ).''I couldn't bold the ascii (pasted) text to also show how cleverly this is written.. So easy to scoop!The book is for a Song on kindle , when I bought it!!!!
Amazon Verified review Amazon
Omid Karimi Jun 09, 2016
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
The development of the material starts good but for the first four chapters, one needs to know more and more about the next chapters before understanding the current chapter. Overall the book starts promising but deteriorates into jumping over important topics.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.