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
$9.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
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.

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
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

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 : 9781849691727
Vendor :
Khronos Group
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 147.97
Responsive Web Design with HTML5 and CSS3
$43.99
WebGL Beginner's Guide
$48.99
OpenGL Development Cookbook
$54.99
Total $ 147.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

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela