Top Related Projects
JavaScript 3D Library.
The Official Khronos WebGL Repository
👑 Functional WebGL
Minimal WebGL Library
The HTML5 Creation Engine: Create beautiful digital content with the fastest, most flexible 2D WebGL renderer.
Babylon.js is a powerful, beautiful, simple, and open game and rendering engine packed into a friendly JavaScript framework.
Quick Overview
WebGL Fundamentals is an educational resource and collection of tutorials aimed at teaching WebGL from the ground up. It provides comprehensive explanations, interactive examples, and practical exercises to help developers understand and implement 3D graphics in web browsers using WebGL.
Pros
- Comprehensive and in-depth coverage of WebGL concepts
- Interactive examples and live demos for better understanding
- Well-structured content, suitable for beginners and intermediate learners
- Regularly updated to include modern WebGL practices and techniques
Cons
- May be overwhelming for absolute beginners in graphics programming
- Requires a solid understanding of JavaScript to fully benefit from the tutorials
- Some advanced topics might need additional resources for complete mastery
- Limited coverage of WebGL 2.0 compared to WebGL 1.0
Code Examples
Here are a few code examples from the WebGL Fundamentals tutorials:
- Setting up a WebGL context:
function createWebGLContext(canvas) {
const gl = canvas.getContext("webgl");
if (!gl) {
console.error("Unable to initialize WebGL. Your browser may not support it.");
return null;
}
return gl;
}
- Creating and compiling a shader:
function createShader(gl, type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.error('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
return shader;
}
- Drawing a simple triangle:
function drawTriangle(gl, program) {
gl.useProgram(program);
const positionAttributeLocation = gl.getAttribLocation(program, "a_position");
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const positions = [
0, 0,
0, 0.5,
0.7, 0,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
gl.enableVertexAttribArray(positionAttributeLocation);
gl.vertexAttribPointer(positionAttributeLocation, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLES, 0, 3);
}
Getting Started
To get started with WebGL Fundamentals:
- Visit the WebGL Fundamentals website.
- Start with the "Fundamentals" section to learn the basics.
- Follow the tutorials in order, experimenting with the interactive examples.
- Use a modern web browser with WebGL support (e.g., Chrome, Firefox, Safari).
- Set up a local development environment with a text editor and a local server.
- Practice by modifying the provided examples and creating your own WebGL projects.
Competitor Comparisons
JavaScript 3D Library.
Pros of three.js
- High-level abstraction, making 3D graphics more accessible
- Extensive documentation and large community support
- Rich set of built-in features and utilities for 3D rendering
Cons of three.js
- Steeper learning curve for those wanting to understand low-level WebGL concepts
- Less flexibility for custom, low-level optimizations
- Larger file size and potential performance overhead
Code Comparison
three.js:
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
WebGL Fundamentals:
const canvas = document.querySelector("#canvas");
const gl = canvas.getContext("webgl");
if (!gl) {
// WebGL not supported
}
// Continue with raw WebGL setup...
The three.js example demonstrates its high-level abstraction, quickly setting up a scene, camera, and renderer. The WebGL Fundamentals example shows the more low-level approach, starting with obtaining the WebGL context directly. This illustrates the trade-off between ease of use and low-level control offered by each approach.
The Official Khronos WebGL Repository
Pros of WebGL
- Official repository maintained by the Khronos Group, ensuring up-to-date and accurate information
- Comprehensive documentation and specifications for WebGL
- Includes conformance tests and sample implementations
Cons of WebGL
- Focuses more on specifications and standards rather than tutorials
- May be less beginner-friendly compared to webgl-fundamentals
- Limited code examples for learning purposes
Code Comparison
WebGL (specification example):
void texImage2D(GLenum target, GLint level, GLint internalformat,
GLsizei width, GLsizei height, GLint border,
GLenum format, GLenum type, const void* pixels);
webgl-fundamentals (tutorial example):
const gl = canvas.getContext("webgl");
const program = webglUtils.createProgramFromScripts(gl, ["vertex-shader-2d", "fragment-shader-2d"]);
gl.useProgram(program);
The WebGL repository provides formal specifications, while webgl-fundamentals offers practical, tutorial-style code examples. WebGL is more suitable for developers seeking official documentation, while webgl-fundamentals is better for those learning WebGL programming through hands-on examples and explanations.
👑 Functional WebGL
Pros of regl
- Higher-level abstraction, simplifying WebGL programming
- Functional approach, promoting composability and reusability
- Automatic state management, reducing boilerplate code
Cons of regl
- Steeper learning curve for those familiar with raw WebGL
- Less fine-grained control over low-level WebGL operations
- Potential performance overhead due to abstraction layer
Code Comparison
webgl-fundamentals:
const gl = canvas.getContext("webgl");
const program = webglUtils.createProgramFromScripts(gl, ["vertex-shader", "fragment-shader"]);
gl.useProgram(program);
// ... (more setup code)
gl.drawArrays(gl.TRIANGLES, 0, 3);
regl:
const regl = require('regl')();
const drawTriangle = regl({
frag: '...',
vert: '...',
attributes: { position: [[-1, -1], [0, 1], [1, -1]] },
count: 3
});
drawTriangle();
regl provides a more concise and declarative approach to WebGL programming, while webgl-fundamentals offers a lower-level, more explicit control over the rendering pipeline. The choice between the two depends on the developer's needs, experience, and project requirements.
Minimal WebGL Library
Pros of OGL
- Higher-level abstraction, making it easier to create complex 3D scenes
- Built-in support for modern WebGL features and optimizations
- More comprehensive set of utilities and helpers for common 3D tasks
Cons of OGL
- Less educational for those wanting to learn raw WebGL
- May have a steeper learning curve for beginners
- Potentially less flexibility for highly custom rendering techniques
Code Comparison
OGL:
const geometry = new Geometry(gl, {
position: {size: 3, data: new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0])},
uv: {size: 2, data: new Float32Array([0, 0, 1, 0, 1, 1])},
});
WebGL Fundamentals:
const positions = [
-1, -1, 0,
1, -1, 0,
1, 1, 0,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
OGL provides a more concise and structured way to define geometry, while WebGL Fundamentals demonstrates the raw WebGL approach, which is more verbose but offers direct control over buffer creation and data assignment.
The HTML5 Creation Engine: Create beautiful digital content with the fastest, most flexible 2D WebGL renderer.
Pros of PixiJS
- High-level API for easier 2D rendering and sprite manipulation
- Extensive documentation and active community support
- Built-in performance optimizations and mobile device support
Cons of PixiJS
- Less flexibility for low-level WebGL operations
- Larger file size due to additional features and abstractions
- Steeper learning curve for developers new to game development
Code Comparison
WebGL Fundamentals:
const gl = canvas.getContext("webgl");
const program = createProgramFromSources(gl, vertexShaderSource, fragmentShaderSource);
gl.useProgram(program);
// ... (more low-level WebGL setup)
PixiJS:
const app = new PIXI.Application();
document.body.appendChild(app.view);
const sprite = PIXI.Sprite.from("image.png");
app.stage.addChild(sprite);
WebGL Fundamentals provides a more hands-on approach to WebGL, offering in-depth understanding of graphics programming concepts. PixiJS, on the other hand, abstracts many low-level details, allowing for rapid development of 2D graphics applications and games. The choice between the two depends on the project requirements and the developer's need for control over WebGL operations versus development speed and ease of use.
Babylon.js is a powerful, beautiful, simple, and open game and rendering engine packed into a friendly JavaScript framework.
Pros of Babylon.js
- Full-featured 3D engine with a higher level of abstraction
- Extensive documentation and community support
- Built-in physics engine and advanced features like PBR rendering
Cons of Babylon.js
- Steeper learning curve for beginners
- Larger file size and potentially higher performance overhead
- Less flexibility for low-level WebGL operations
Code Comparison
WebGL Fundamentals:
const gl = canvas.getContext("webgl");
const program = webglUtils.createProgramFromScripts(gl, ["vertex-shader", "fragment-shader"]);
gl.useProgram(program);
Babylon.js:
const engine = new BABYLON.Engine(canvas, true);
const scene = new BABYLON.Scene(engine);
const camera = new BABYLON.FreeCamera("camera", new BABYLON.Vector3(0, 5, -10), scene);
WebGL Fundamentals provides a more hands-on approach to learning WebGL, focusing on the fundamentals and low-level operations. It's excellent for understanding the core concepts of WebGL programming.
Babylon.js, on the other hand, is a comprehensive 3D engine built on top of WebGL. It offers a higher level of abstraction, making it easier to create complex 3D applications quickly. However, this comes at the cost of less control over low-level operations and a larger learning curve for those new to 3D graphics programming.
Choose WebGL Fundamentals for in-depth learning of WebGL concepts, or Babylon.js for rapid development of feature-rich 3D applications.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
WebGL Fundamentals
This is a series of lessons or tutorials about WebGL.
Unlike most WebGL lessons these are not based off of OpenGL. OpenGL is 20 years old. The lessons of OpenGL don't match well with WebGL. The APIs have changed too much. The ideas of OpenGL and OpenGL tutorials are out of date with WebGL, OpenGL ES 2.0 and the land of shaders.
I would argue that WebGL is actually a very simple API. What makes it appear complicated is the way in which it's used. The complications are added by the programmer. WebGL itself is simple.
These lessons try to show that simplicity as well as teach the fundamentals of 2D math and 3D math so readers can hopefully have an easier time writing their own WebGL programs and understanding the complexity that other programmers pile on top of simple WebGL.
This is work in progress. Feel free to contribute.
Contributing
Of course bug fixes are always welcome.
If you'd like to write a new article please try to always take one step at a time. Don't do 2 or more things in a single step. Explain any new math in the simplest terms possible. Ideally with diagrams where possible.
Translating
Each translation goes in a folder under webgl/lessons/<country-code>
.
Required files are
langinfo.hanson
index.md
toc.html
langinfo.hanson
Defines various language specific options. Hanson is a JSON like format but allows comments.
Current fields are
{
// The language (will show up in the language selection menu)
language: 'English',
// Phrase that appears under examples
defaultExampleCaption: "click here to open in a separate window",
// Title that appears on each page
title: 'WebGL Fundamentals',
// Basic description that appears on each page
description: 'Learn WebGL from the ground up. No magic',
// Link to the language root.
link: 'https://webglfundamentals.org/webgl/lessons/ja', // replace `ja` with country code
// html that appears after the article and before the comments
commentSectionHeader: '<div>Issue/Bug? <a href="https://github.com/gfxfundamentals/webgl-fundamentals/issues">Create an issue on github</a>.</div>',
// markdown that appears for untranslated articles
missing: "Sorry this article has not been translated yet. [Translations Welcome](https://github.com/gfxfundamentals/webgl-fundamentals)! ð\n\n[Here's the original English article for now]({{{origLink}}}).",
// the phrase "Table of Contents"
toc: "Table of Contents",
// translation of categories for table of contents
categoryMapping: {
'fundamentals': "Fundamentals",
'image-processing': "Image Processing",
'matrices': "2D translation, rotation, scale, matrix math",
'3d': "3D",
'lighting': "Lighting",
'organization': "Structure and Organization",
'geometry': "Geometry",
'textures': "Textures",
'rendertargets': "Rendering To A Texture",
'2d': "2D",
'text': "Text",
'misc': "Misc",
'reference': "Reference",
},
}
index.md
This is the template for the main page for each language
toc.html
This is template for the table of contents for the language.
It is included on both the index and on each article. The only
parts not auto-generated are the links ending links which
you can translate if you want to.
The build system will create a placeholder for every English article for which there is no corresponding article in that language. It will be filled with the missing
message from above.
lang.css
This is included if and only if it exists. I'd strongly prefer not to have to use it. In particular I don't want people to get into arguments about fonts but basically it's a way to choose the fonts per language. You should only set the variables that are absolutely needed. Example
/* lessons/ko/lang.css */
/* Only comment in overrides as absolutely necessary! */
:root {
--article-font-family: "best font for korean article text";
--headline-font-family: "best font for korean headlines";
/* a block of code */
/* --code-block-font-family: "Lucida Console", Monaco, monospace; */
/* a word in a sentence */
/* --code-font-family: monospace; */
}
Notice 2 settings are not changed. It seems unlikely to me that code would need a different font per language.
PS: While we're here, I love code fonts with ligatures but they seem like a bad idea for a tutorial site because the ligatures hide the actual characters needed so please don't ask for or use a ligature code font here.
Translation notes
The build process will make a placeholder html file for each article that has an English .md file in
webgl/lessons
but no corresponding .md file for the language. This is to make it easy to include
links in an article that links to another article but that other article has not yet been translated.
This way you don't have to go back and fix already translated articles. Just translate one article
at a time and leave the links as is. They'll link to placeholders until someone translates the missing
articles.
Articles have front matter at the top
Title: Localized Title of article
Description: Localized description of article (used in RSS and social media tags)
TOC: Localized text for Table of Contents
DO NOT CHANGE LINKS : For example a link to a local resources might look like
[text](link)
or
<img src="somelink">
While you can add query parameters (see below) do not add "../" to try to make the link relative to the .md file. Links should stay as though the article exists at the same location as the original English.
UI localization
Some of the diagrams allow passing translations for the UI and other text.
For example if there is a slider named "rotation"
you can add "?ui-rotation=girar" at the end of the URL for the diagram. For 2 or more translations
separate them with a &
. Certain characters are disallowed in URLs like =
, #
, &
etc. For those
use their uri encoding.
For diagram labels you'll have to look inside the code. For example for the directional lighting diagram near the start of the code it looks like this
const lang = {
lightDir: opt.lightDir || "light direction",
dot: opt.dot || "dot(reverseLightDirection,surfaceDirection) = ",
surface1: opt.surface1 || "surface",
surface2: opt.surface2 || "direction",
};
Which means you can localize the labels like this
{{{diagram url="resources/directional-lighting.html?lightDir=å
ç·æ¹å&surface1=ãªãã¸ã§ã¯ã&surface2=è¡¨é¢æ¹å&dot=dot(å
ç·å対æ¹å,è¡¨é¢æ¹å)%20%3D%20&ui-rotation=è§åº¦" caption="æ¹åãå転ãã¦ã¿ã¦" width="500" height="400"}}}
For testing, reference the sample directly in your browser. For example
To build
The site is built into the out
folder
Steps
git clone https://github.com/gfxfundamentals/webgl-fundamentals.git
cd webgl-fundamentals
npm install
npm run build
npm start
now open your browser to http://localhost:8080
Continuous build
You can run npm run watch
after you've built to get continuous building.
Only the article .md files and files that are normally copied are watched.
The index files (the top page with the table of contents) is not regenerated
nor does changing a template rebuild all the articles.
Build options
This is mostly for debugging build.js
. Since it takes a while to process all the files
you can set ARTICLE_FILTER
to a substring of the filenames to process. For example
ARTICLE_FILTER=rotation npm run build
Will build the site as though only articles with rotation
in their filename exist.
TO DO
A list of articles I'd like to write or see written
- lighting
- normal maps
- geometry
- plane, cube, sphere, cone, disc, torus
- lines vs triangles
- vertex colors
- other
- pre-process (don't load .obj, .dae, .fbx etc at runtime)
- pre-optimize (texture atlas, sizes, combine meshes, etc...)
- plane, cube, sphere, cone, disc, torus
- animation
- blendshapes
- hierarchical animation
- debugging
- debugging JS WebGL
- example (https://goo.gl/8U5whT)
- CHECK THE GAWD DAMN CONSOLE!
- actually read the error message
- understand it.
- INVALID_ENUM means one of your gl.XXX values is not valid period
- INVALID_VALUE means one of the int or float values is probably off
- INVALID_OPERATION means something you tried to do won't work for the given state
- texture not renderable
- attribute out of range
- check your framebuffers
- check your extensions
- make shorter samples (MCVE)
- remove any code you don't need
- get rid of CSS
- get rid of HTML
- consider using a POINT (no attributes needed)
- don't use images if they are not relevant. Use a canvas or a single and double pixel texture
- While creating this MCVE you'll often find the bug
- debugging a shader
- set fragment shader to solid color.
- render normals
- render texcoords
- render cube/sphere/plane
- debugging JS WebGL
- text
- glyph cache
- post processing
- DOF
- glow
- light rays
- RGB glitch, CRT distortion, scanlines
- color mapping/tone mapping
- Creative coding
- color palettes
- tilemaps
- generated geometry
- histogram
- particles
- toon/ramp shading
- procedural textures
- code organization
- scene graph
- putting lights and camera in scene graph
- scene graph
- Engine Creation
- culling
- frustum culling
- grid culling
- quad tree / oct tree
- portals (is this still a thing?)
- PVS
- materials
- lighting DB
- culling
- Physically based rendering
Top Related Projects
JavaScript 3D Library.
The Official Khronos WebGL Repository
👑 Functional WebGL
Minimal WebGL Library
The HTML5 Creation Engine: Create beautiful digital content with the fastest, most flexible 2D WebGL renderer.
Babylon.js is a powerful, beautiful, simple, and open game and rendering engine packed into a friendly JavaScript framework.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot