WebGL - Examples - Help
Poly Edges
Set the number of outside edges in the polygon. Triangle is 3, square is 4, pentagon is 5, etc.
The more edges, the more circular the polygon becomes.
Tessellation
Set the the number of times tessellation is applied to the polygon.
The more tessellations, the more curved the twisted polygon becomes.
Twist Angle Set the angle used in the twist transformation.
Mesh (or Filled) Draw the polygon as triangle mesh outlines or as a filled solid.
Tri-Mid (or Tri-Edge) Draw the triangles forming the polygon from the middle or the edge of the polygon.
GPU (or CPU) Calculate the twisted points in the GPU or the CPU.
Elements (or Arrays) Draw the polygon using gl.drawElements or gl.drawArrays.
Concepts demonstrated on this page- Drawing mesh outlines and polygons made of triangles
- Tessellating (sub-dividing) triangles
- WebGL drawing using gl.drawElements versus gl.drawArrays
-
Basic shader functionality
- using attribute and uniform variables
- setting gl_Position with a twist transformation in the vertex shader
- passing calculated color values from the vertex shader to the fragment shader using a varying variable
- setting gl_FragColor in the fragment shader
- WebGL precision qualifiers
- Handling lost context
- HTML range and number input (see Web Dev)
More information is available in the source code (see Web Dev for information on how to view source code).
Draw Mode Set the currently active draw mode. Each draw mode acts like a separate layer in the scene; moving points and selection only works on the points in the current draw mode.
Selection Set the points that are drawn in the current draw mode; defaults to all. Acts as a simplfied undo.
Clear Screen Clears all points from all draw modes.
Point Size Set the point size.
Square, Round or Hollow Points Set the point style.
Mouse Interaction
Click in the canvas to add a new point to the current draw mode. If close to an existing point, adds a new point at the existing point.
Click near an existing point and drag to move it. Release near an existing point to combine the points.
- WebGL draw modes (also see Table 3.3 and Figure 3.13)
- Using multiple draw calls in a render loop
-
Shader functionality
- conversion from canvas coodrinates to clip coordinates
- setting gl_PointSize in the vertex shader
- reading gl_PointCoord in the fragment shader to draw different point styles
- using discard in the fragment shader to skip drawing a fragment
- Adjusting the geometry when the canvas size changes
- Mouse and touch interaction with objects drawn in the canvas
- HTML select input (see Web Dev)
More information is available in the source code (see Web Dev for information on how to view source code).
This page demonstrates drawing lines with different line widths, segment sizes and colors.
gl.lineWidth has limited range on some platforms.
Click here to test your machines capability.
Click here to read more about the limitations.
Drawing lines using triangles is a workaround for this limitation.
Triangles are drawn around the midline (the actual line).
The line width determines the distance on either side of the actual line.
The line segments determine the jaggedness of the lines, with smaller segments appearing more curved.
The first line shown is drawn as a triangle strip so line segments are connected by 2 triangles, resulting in a smoother join.
The second line shown is drawn as unconnected triangles (no smoothing), resulting in jagged gaps in the line.
Here are 2 line drawing resources.
Drawing Lines is Hard
Rendering with Line Primitives
Clear the screen to draw your own lines.
This page demonstrates multiple attributes, drawing partial buffers, sub-buffering, manipulating objects and the use of basic matrix transformations.
You can place multiple polygon objects of different shapes, sizes and colors and manipulate their position, size, rotation and colors after creation.
To create a polygon:
- Set the number of edges to determine the shape of the polygon.
- Click create polygon and move the mouse to the position in the canvas where you want to place the object.
- Click the left mouse button and hold and drag to size the object.
- Release the left mouse button to finish the creation of the polygon.
When you move the mouse over the polygon the outline will highlight in yellow. When you click on a polygon the object will be selected and the triangles making up the object will draw in white. Select a color mode and click change colors to assign new random colors to the vertices, triangles or whole polygon of the selected object.
To reposition a polygon:
- Select a polygon
- Click the left mouse button and hold and drag to position the object.
- Release the left mouse button to finish the movement of the polygon.
To resize a polygon:
- Select a polygon
- Scroll the mouse wheel to resize the polygon, up is larger, down is smaller.
To rotate a polygon:
- Select a polygon
- Click the right mouse button and hold and drag around the objects center to rotate the object.
- Release the right mouse button to finish the rotation of the polygon.
Refresh the page to clear the canvas.
This page demonstrates 3-dimensional orthographic and perspective viewing, depth test hidden surface removal and more complex matrix transformations.
This page is still a work in progress has is buggy.
The model, view and projection matrices are the standard ways to handle positioning and clipping within the scene. The model matrix positions and shapes the objects within the scene. The view matrix orients the scene according to the viewer. The projection matrix clips the scene to the drawing window, and can be used to provide zooming functionality and perspective.
Use the model transform controls to rotate, scale and translate the triangle objects and change the model matrix. The model matrix can also be changed directly, but the model transform controls cannot be synced with these changes.
Use the view look at entries to modify the view matrix. The eye position represents the viewers position in the scene. The at position is the location the viewer is looking at. The up vector orients the viewer indicating which direction is towards the top of the canvas. The view matrix can also be modified directly, but the view controls cannot be synced with the changes.
The orthographic, frustum and perspective controls modify the projection matrix. Orthographic provides a rectangular clipping volume from left, right, top, bottom, near and far positions. Frustum uses the same information to clip but adds perspective. The perspective controls are an alternative way to specify the projection matrix with perspective. The projection matrix can also be modified directly, but the projection controls cannot be synced with the changes.
A more visual way to modify these matricies is using the view navigation control at the top left of the canvas. This control allows rotation, panning and zooming of the view. It is also possible to zoom using the mouse wheel and pan and rotate using mouse dragging by turning on the drag mode.
The last matrix that can be modified is the combined matrix, which is the projection * view * model matrix. These changes cannot be synced back to any of the previous controls.
Viewing is a very complicated topic to understand. Below are some links to other resources to help make this more understandable.
Resources
Homogeneous Coordinates and Transformation Matrices
Wikipedia - Orthographic projection
WebGL 3D Perspective
OpenGL Projection Matrix
Calculating the gluPerspective matrix and other OpenGL matrix maths
This page demonstrates creating meshes for 3-dimensional objects, basic shading and transparency, culling, polygon offset and more functionality in the vertex shader.
Polygon meshes are generated proceduarlly. Each mesh contains information about the vertices, triangles, polygons, and surfaces making up the object. The basic classes of shapes are plane, cone, cylinder, dome, capsule and torus. By adjusting the divisions in the objects, a much wider variety of shapes can be created, and can increase the appearance of curvature. Color is scaled by distance to give filled polygons some shading to accentuate their shape.
The polygon plane is 2-dimensional and can have any number of edges. The triangle and rectangle are special optimized cases of the polygon.
The cone, cylinder, dome and torus objects begin as polygon bases. The bases are projected in various ways to generate closed surfaces. The capsule objects are compound objects.
The cone is projected up to a point and connected from the polygon edges to the apex by triangular sides. It can also be projected down for a 2-sided cone (diamond).
The cylinder is projected up and down and connected by rectangular sides which are divided into 2 triangles. The cube is an omptimized case of a cylinder with 4 edges.
The dome is similar to the cone, but vertical divisions are created along an arc up to the apex point. A 2-sided dome becomes a sphere with enough divisions.
To create a torus a polygon is projected around a circular arc at given angular divisions and at a given radius from the origin.
The capsule is a cylinder with domes used as the end caps.
Many options can be played with to view, transform and create variations on the objects. Experimentation is the best way to learn what they do.
This page demonstrates more complex vertex and fragment shader functionality, multiple shaders and lighting effects comparing the GPU versus the CPU.
Lighting is a combination of emissive, ambient, diffuse and specular colors from the object and the light source.
Diffuse lighting produces shaded coloring based on the angle between the surface normal and a light vector. Specular lighting produces the highlights based on the angle between the viewer and a reflected light vector. Ambient lighting produces flat shading and models the remaining light bouncing around the environment. Emissive lighting also produces flat shading, but models light coming from the surface of an object.
The primary difference between lighting using the CPU versus the GPU is performance. This is easy to see by switching to CPU light mode and rotating the view around a sphere with 100 edges and 25 vertical divisions. Response is very slow because the CPU can't keep up with the calculations. Switching to GPU vertex light mode changes nothing on the image, but performance increases dramatically.
The difference between lighting in the vertex shader (Gouraud shading) and the fragment shader (Phong shading) is image quality. Phong shading produces smoother more precise coloring and can be best seen in the specular hightlights and spot light cutoff. Switch back and forth between GPU vertex light mode and GPU fragment light mode to see the differences. Another important difference is that front and back faces can be distinguished between in the fragment shader. Change the shape to polygon and view the back side. In CPU or GPU vertex light mode the back is lit, in GPU fragment mode it is dark as it should be.
There are 3 light types: point, directional and spot, each producing different lighting effects. Normals for the shapes can be generated in multiple ways producing different shading effects. Plus other lighting and material options can be modified for further effects. Experimentation is the best way to see how they work.
Here is a resource to help understand lighting.
WikiBooks - GLSL Programming - Basic Lighting
This page demonstrates texturing in the shader, assigning texture coordinates with different algorithms and some of the texture options available in WebGL.
Texture coordinates can be assigned using a variety of object specific, planar, cylindrical and spherical algorithms. Planar will apply coordinates in 2 axes and leave the 3rd axis constant. Cylindrical will wrap the coordinates around an axis of the object. Spherical will also wrap around an axis of the object, but also bends towards an apex point. Each algorithm will distort the texture in different ways and some will work better for different objects or different usage scenarios.
There are many options to experiment with to modify the texture.
Textures coordinates can be transformed to alter their location on the object.
Wrapping and clamping options are available and affect how textures look when the texture is not matched exactly to the object dimensions.
Filtering can be applied to smooth textures in different zooming scenarios.
Here is another explanation of some of the texture options available.
There are also many ways to apply textures to the object. Click on the texture button to load files from your computer. Click on the texture picture to load procedurally generated textures (checker or swirl) or the default images I have provided. Textures can also be loaded using drag and drop functionality. Drag onto the texture picture from either your computer or another website (if the website allows cross domain images).
Textures can also be applied to the individual color components as well as overlayed and mixed using a variety of different mechanisms. This tool allows seperate ambient, diffuse and specular textures and an overlay texture that can be mixed with the diffuse texture using information from a blend texture.
Textures options are very numerous and it can be difficult to figure out what is going on. Changing shapes, shape options, triangle mode, normal mode, texture coordinate mode and tessellation will all have an impact on the texturing output. Experimentation is the only way to start to figure out how this all fits together.
Here are another couple of resources to help understand texturing.
MDN - Using textures in WebGL
WikiBooks - GLSL Programming - Basic Texturing
This page demonstrates bump and normal mapping in WebGL. It is still a work in progress.
Bump Mapping uses a gray scale height map image to provide modifications to the existing normals.
Normal Mapping uses an image map to provide normal information by mapping RGB values to XYZ normal coordinates.
More information is available in the source code (see Web Dev for information on how to view source code).
General Topics
WebGL best practices
WebGL precision qualifiers
Handling lost context
WebGL Debugging
References
WebGL Programming Guide - Textbook
WikiBooks - GLSL Programming - Tutorials & Reference
(see GLSL in OpenGL until GLSL in HTML5 is complete)
Google Searching Web development is a very well covered subject and Google searches will provide answers to almost anything you can think of. Someone else has probably already solved the problem.
Viewing Source Code In general, right click on the page and select view source. Do not right click on an image, hyperlink, canvas, etc, as they have different context menus. If right click is not available, the source is also available in the developer tools.
Developer Tools In most browsers press F12 to access the developer tools. All HTML, CSS and JavaScript source files are available. The console allows you to interactively play around with JavaScript, either to maniulate the current page, or just general exploring.
HTML Input Controls
Range Input
In order to get instant feedback on the range input, set the oninput handler.
Internet Explorer does not react to the range oninput handler, but provides instant feedback with the onchange handler.
Don't use both as non-IE browsers will trigger twice.
Instead test for IE using, navigator.userAgent.indexOf("Trident").
Browser detection
is generally a bad idea, but I have not come up with or found a good feature detection alternative.
Number Input
The number input can be a good alternative to the range input, at least for Chrome and Firefox users,
where the control has increment and decrement functionality built-in.
To be most flexible a synced combination of range and number inputs may be the answer.
Select Input
The change event in Firefox behaves a little differently than other browsers.
Using the keyboard to move through options does not trigger the change event in Firefox, until the focus is lost or the enter key is pressed.
References
W3Schools.com - HTML, CSS, JavaScript, jQuery, Bootstrap, HTML Graphics - Tutorials & Reference
Bootstrap Glyphicons
A Complete Guide to Flexbox
Learning JavaScript Design Patterns - Online Textbook