### WebGL Setup and Texture Loading Example
Source: https://webglfundamentals.org/webgl/lessons/webgl-cors-permission.html
This is a basic WebGL setup that includes getting a context, creating a shader program, and looking up attribute and uniform locations. It also includes buffer creation and is intended to demonstrate texture loading, though cross-origin textures will fail.
```javascript
"use strict";
function main() {
// Get A WebGL context
/** @type {HTMLCanvasElement} */
var canvas = document.querySelector("#canvas");
var gl = canvas.getContext("webgl");
if (!gl) {
return;
}
// setup GLSL program
var program = webglUtils.createProgramFromScripts(gl, ["vertex-shader", "fragment-shader"]);
// look up where the vertex data needs to go.
var positionLocation = gl.getAttribLocation(program, "a_position");
var texcoordLocation = gl.getAttribLocation(program, "a_texcoord");
// lookup uniforms
var matrixLocation = gl.getUniformLocation(program, "u_matrix");
var textureLocation = gl.getUniformLocation(program, "u_texture");
// Create a buffer.
var positionBuffer = gl.createBuffer();
```
--------------------------------
### WebGL Initialization and Setup
Source: https://webglfundamentals.org/webgl/lessons/webgl-fog.html
Basic WebGL setup including getting the context, creating a shader program, and locating vertex attributes and uniforms.
```javascript
"use strict";
function main() {
// Get A WebGL context
/** @type {HTMLCanvasElement} */
var canvas = document.querySelector("#canvas");
var gl = canvas.getContext("webgl");
if (!gl) {
return;
}
// setup GLSL program
var program = webglUtils.createProgramFromScripts(gl, ["vertex-shader-3d", "fragment-shader-3d"]);
// look up where the vertex data needs to go.
var positionLocation = gl.getAttribLocation(program, "a_position");
var texcoordLocation = gl.getAttribLocation(program, "a_texcoord");
// lookup uniforms
var projectionLocation = gl.getUniformLocation(program, "u_projection");
```
--------------------------------
### Full WebGL Example Setup
Source: https://webglfundamentals.org/webgl/lessons/webgl-drawing-without-data.html
This code block provides a complete, runnable example including canvas setup, GLSL shader definitions, and the JavaScript render loop. It demonstrates drawing points procedurally without explicit vertex data.
```javascript
'use strict';
const gl = document.querySelector('#c').getContext('webgl');
const vs = `
attribute float vertexId;
uniform float numVerts;
uniform float time;
void main() {
float u = vertexId / numVerts; // goes from 0 to 1
float x = u * 2.0 - 1.0; // -1 to 1
float y = fract(time + u) * -2.0 + 1.0; // 1.0 -> -1.0
gl_Position = vec4(x, y, 0, 1);
gl_PointSize = 5.0;
}
`;
const fs = `
precision mediump float;
void main() {
gl_FragColor = vec4(0, 0, 1, 1);
}
1
1
@import url("https://webglfundamentals.org/webgl/resources/webgl-tutorials.css");
WebGLFundamentals
Export To:
jsGist Codepen JSFiddle Stack Overflow
Copy and paste the text below into a stack overflow question.
```
```
click here to open in a separate window
This gives us POINTS going down the screen but they are all in order. We need to add some randomness. There is no random number generator in GLSL. Instead we can use a function that generates something that appears random enough.
Here's one
```
* // hash function from https://www.shadertoy.com/view/4djSRW
* // given a value between 0 and 1
* // returns a value between 0 and 1 that *appears* kind of random
* float hash(float p) {
* vec2 p2 = fract(vec2(p * 5.3983, p * 5.4427));
* p2 += dot(p2.yx, p2.xy + vec2(21.5351, 14.3137));
* return fract(p2.x * p2.y * 95.4337);
* }
and we can use that like this
```
* void main() {
* float u = vertexId / numVerts; // goes from 0 to 1
* float x = u * 2.0 - 1.0; // -1 to 1
* float x = hash(u) * 2.0 - 1.0; // random position
* float y = fract(time + u) * -2.0 + 1.0; // 1.0 -> -1.0
* * gl_Position = vec4(x, y, 0, 1);
* gl_PointSize = 5.0;
* }
We pass `hash` our previous 0 to 1 value and it gives us back a pseudo random 0 to 1 value.
Let's also make the points smaller
```
```
--------------------------------
### Basic WebGL Program Setup
Source: https://webglfundamentals.org/webgl/lessons/webgl-qna-webgl-droste-effect.html
A minimal WebGL setup including shader definitions and context retrieval. This serves as a starting point for WebGL applications.
```javascript
"use strict";
function main() {
const m4 = twgl.m4;
const gl = document.querySelector('canvas').getContext('webgl')
const vs = `
attribute vec4 position;
attribute vec2 texcoord;
uniform mat4 u_matrix;
varying vec2 v_texcoord;
void main() {
gl_Position = u_matrix * position;
v_texcoord = texcoord;
}
`;
const fs = `
precision mediump float;
varying vec2 v_texcoord;
uniform sampler2D u_tex;
void main() {
gl_FragColor = texture2D(u_tex, v_texcoord);
}
1
`
```
--------------------------------
### JavaScript: Full Example Setup
Source: https://webglfundamentals.org/webgl/lessons/webgl-qna-emulating-palette-based-graphics-in-webgl.html
Sets up the WebGL context, creates and uses a shader program, and configures texture units for the image and palette. Assumes `twgl.js` is available for `createProgramFromScripts`.
```javascript
var canvas = document.getElementById("c");
var gl = canvas.getContext("webgl");
// Note: createProgramFromScripts will call bindAttribLocation
// based on the index of the attibute names we pass to it.
var program = twgl.createProgramFromScripts(
gl,
["vshader", "fshader"],
["a_position", "a_textureIndex"]);
gl.useProgram(program);
var imageLoc = gl.getUniformLocation(program, "u_image");
var paletteLoc = gl.getUniformLocation(program, "u_palette");
// tell it to use texture units 0 and 1 for the image and palette
gl.uniform1i(imageLoc, 0);
gl.uniform1i(paletteLoc, 1);
// Setup a unit quad
var positions = [
1, 1,
-1, 1,
-1, -1,
1, 1,
-1, -1,
1, -1,
1
1
canvas { border: 1px solid black; }
WebGLFundamentals
Export To:
jsGist Codepen JSFiddle Stack Overflow
Copy and paste the text below into a stack overflow question.
```
```
click here to open in a separate window
```
--------------------------------
### Full Example Setup with WebGL and Canvas 2D
Source: https://webglfundamentals.org/webgl/lessons/webgl-text-canvas2d.html
Initializes WebGL context, retrieves the 2D context for text rendering, and sets up shaders.
```javascript
"use strict";
function main() {
// Get A WebGL context
/** @type {HTMLCanvasElement} */
var canvas = document.querySelector("#canvas");
var gl = canvas.getContext("webgl");
if (!gl) {
return;
}
// look up the text canvas.
var textCanvas = document.querySelector("#text");
// make a 2D context for it
var ctx = textCanvas.getContext("2d");
// setup GLSL program
var program = webglUtils.createProgramFromScripts(gl, ["vertex-shader-3d", "fragment-shader-3d"]);
// look up where the vertex data needs to go.
var positionLocation = gl.getAttribLocation(program, "a_position");
var colorLocation = gl.getAttribLocation(program, "a_color");
```
--------------------------------
### Basic WebGL Setup
Source: https://webglfundamentals.org/webgl/lessons/webgl-fog.html
Standard setup for a WebGL application, including getting the canvas context, creating a shader program, and looking up attribute and uniform locations.
```javascript
"use strict";
function main() {
// Get A WebGL context
/** @type {HTMLCanvasElement} */
var canvas = document.querySelector("#canvas");
var gl = canvas.getContext("webgl");
if (!gl) {
return;
}
// setup GLSL program
var program = webglUtils.createProgramFromScripts(gl, ["vertex-shader-3d", "fragment-shader-3d"]);
// look up where the vertex data needs to go.
var positionLocation = gl.getAttribLocation(program, "a_position");
var texcoordLocation = gl.getAttribLocation(program, "a_texcoord");
// lookup uniforms
var projectionLocation = gl.getUniformLocation(program, "u_projection");
var worldViewLocation = gl.getUniformLocation(program, "u_worldView");
var textureLocation = gl.getUniformLocation(program, "u_texture");
var fogColorLocation = gl.getUniformLocation(program, "u_fogColor");
var fogNearLocation = gl.getUniformLocation(program, "u_fogNear");
```
--------------------------------
### Complete WebGL Example Setup
Source: https://webglfundamentals.org/webgl/lessons/webgl-drawing-without-data.html
Provides the full HTML, JavaScript, and GLSL code for rendering a circle of points without explicit vertex data buffers.
```javascript
'use strict';
const gl = document.querySelector('#c').getContext('webgl');
const vs = `
attribute float vertexId;
uniform float numVerts;
uniform vec2 resolution;
#define PI radians(180.0)
void main() {
float u = vertexId / numVerts; // goes from 0 to 1
float angle = u * PI * 2.0; // goes from 0 to 2PI
float radius = 0.8;
vec2 pos = vec2(cos(angle), sin(angle)) * radius;
float aspect = resolution.y / resolution.x;
vec2 scale = vec2(aspect, 1);
gl_Position = vec4(pos * scale, 0, 1);
gl_PointSize = 5.0;
}
`;
1
1
@import url("https://webglfundamentals.org/webgl/resources/webgl-tutorials.css");
WebGLFundamentals
Export To:
```
--------------------------------
### WebGL Setup for 3D Textures
Source: https://webglfundamentals.org/webgl/lessons/webgl-3d-textures.html
Basic WebGL setup including getting the context, creating a shader program, and looking up attribute and uniform locations for vertex and fragment shaders.
```javascript
"use strict";
function main() {
// Get A WebGL context
/** @type {HTMLCanvasElement} */
var canvas = document.querySelector("#canvas");
var gl = canvas.getContext("webgl");
if (!gl) {
return;
}
// setup GLSL program
var program = webutils.createProgramFromScripts(gl, ["vertex-shader-3d", "fragment-shader-3d"]);
// look up where the vertex data needs to go.
var positionLocation = gl.getAttribLocation(program, "a_position");
var texcoordLocation = gl.getAttribLocation(program, "a_texcoord");
// lookup uniforms
var matrixLocation = gl.getUniformLocation(program, "u_matrix");
var textureLocation = gl.getUniformLocation(program, "u_texture");
// Create a buffer for positions
var positionBuffer = gl.createBuffer();
```
--------------------------------
### Full WebGL Setup with Indexed Vertices
Source: https://webglfundamentals.org/webgl/lessons/webgl-indexed-vertices.html
This is a complete WebGL example demonstrating the setup of a program, attribute and uniform locations, and buffer creation for drawing with indexed vertices. It includes boilerplate code for context and program creation.
```javascript
"use strict";
function main() {
// Get A WebGL context
/** @type {HTMLCanvasElement} */
var canvas = document.querySelector("#canvas");
var gl = canvas.getContext("webgl");
if (!gl) {
return;
}
// setup GLSL program
var program = webglUtils.createProgramFromScripts(gl, ["vertex-shader-2d", "fragment-shader-2d"]);
// look up where the vertex data needs to go.
var positionAttributeLocation = gl.getAttribLocation(program, "a_position");
// look up uniform locations
var resolutionUniformLocation = gl.getUniformLocation(program, "u_resolution");
var colorUniformLocation = gl.getUniformLocation(program, "u_color");
// Create a buffer to put three 2d clip space points in
var positionBuffer = gl.createBuffer();
}
```
--------------------------------
### Setup WebGL Program and Buffers (Deep Screen Example)
Source: https://webglfundamentals.org/webgl/lessons/webgl-3d-textures.html
Initializes WebGL context, creates a shader program, and sets up buffers for vertex attributes. This snippet is part of an example demonstrating textures on polygons that recede deeply into the screen.
```javascript
"use strict";
var zDepth = 50;
function main() {
// Get A WebGL context
var canvas = document.querySelector("#canvas");
var gl = canvas.getContext("webgl", {antialias: false});
if (!gl) {
return;
}
// setup GLSL program
var program = webglUtils.createProgramFromScripts(gl, ["vertex-shader-3d", "fragment-shader-3d"]);
// look up where the vertex data needs to go.
var positionLocation = gl.getAttribLocation(program, "a_position");
```
--------------------------------
### Basic WebGL Setup and Primitive Creation
Source: https://webglfundamentals.org/webgl/lessons/webgl-less-code-more-fun.html
This snippet shows the fundamental setup for a WebGL application, including getting the context and creating basic geometry buffers using a utility function.
```javascript
"use strict";
function main() {
// Get A WebGL context
/** @type {HTMLCanvasElement} */
var canvas = document.querySelector("#canvas");
var gl = canvas.getContext("webgl");
if (!gl) {
return;
}
var buffers = window.primitives.createSphereBuffers(gl, 10, 48, 24);
```
--------------------------------
### Setup WebGL Program and Get Locations
Source: https://webglfundamentals.org/webgl/lessons/webgl-environment-maps.html
Initializes the WebGL context, creates a GLSL program, and retrieves attribute and uniform locations for vertex and fragment shaders. This is a standard setup for most WebGL applications.
```javascript
"use strict";
function main() {
// Get A WebGL context
/** @type {HTMLCanvasElement} */
var canvas = document.querySelector("#canvas");
var gl = canvas.getContext("webgl");
if (!gl) {
return;
}
// setup GLSL program
var program = webglUtils.createProgramFromScripts(gl, ["vertex-shader-3d", "fragment-shader-3d"]);
// look up where the vertex data needs to go.
var positionLocation = gl.getAttribLocation(program, "a_position");
var normalLocation = gl.getAttribLocation(program, "a_normal");
// lookup uniforms
var projectionLocation = gl.getUniformLocation(program, "u_projection");
var viewLocation = gl.getUniformLocation(program, "u_view");
var worldLocation = gl.getUniformLocation(program, "u_world");
var textureLocation = gl.getUniformLocation(program, "u_texture");
var worldCameraPositionLocation = gl.getUniformLocation(program, "u_worldCameraPosition");
```
--------------------------------
### WebGL Setup with Heightmap Loading
Source: https://webglfundamentals.org/webgl/lessons/webgl-qna-how-to-import-a-heightmap-in-webgl.html
This snippet shows the WebGL context and shader setup, similar to the flat grid example, but intended for use after loading a heightmap image.
```javascript
function run() {
const gl = document.querySelector('canvas').getContext('webgl');
const vs = `
attribute vec4 position;
uniform mat4 matrix;
void main() {
gl_Position = matrix * position;
}
`;
const fs = `
precision highp float;
void main() {
gl_FragColor = vec4(0, 1, 0, 1);
}
`;
const program = twgl.createProgram(gl, [vs, fs]);
const positionLoc = gl.getAttribLocation(program, 'position');
```
--------------------------------
### Full WebGL Setup and Drawing with Translation
Source: https://webglfundamentals.org/webgl/lessons/webgl-2d-translation.html
This is a complete JavaScript example setting up a WebGL context, compiling shaders, creating buffers, and drawing a shape with translation. It highlights how translation is handled by uniforms, making the drawing code simpler.
```javascript
"use strict";
function main() {
// Get A WebGL context
/** @type {HTMLCanvasElement} */
var canvas = document.querySelector("#canvas");
var gl = canvas.getContext("webgl");
if (!gl) {
return;
}
// setup GLSL program
var program = webglUtils.createProgramFromScripts(gl, ["vertex-shader-2d", "fragment-shader-2d"]);
gl.useProgram(program);
// look up where the vertex data needs to go.
var positionLocation = gl.getAttribLocation(program, "a_position");
// lookup uniforms
var resolutionLocation = gl.getUniformLocation(program, "u_resolution");
var colorLocation = gl.getUniformLocation(program, "u_color");
var translationLocation = gl.getUniformLocation(program, "u_translation");
// Create a buffer to put positions in
1
1
@import url("https://webglfundamentals.org/webgl/resources/webgl-tutorials.css");
WebGLFundamentals
Export To:
jsGist Codepen JSFiddle Stack Overflow
Copy and paste the text below into a stack overflow question.
click here to open in a separate window
```
--------------------------------
### Setup WebGL Program and Get Locations
Source: https://webglfundamentals.org/webgl/lessons/webgl-3d-orthographic.html
Initializes the WebGL context, creates a GLSL program from scripts, and retrieves attribute and uniform locations for vertex data and transformation matrices.
```javascript
var program = webglUtils.createProgramFromScripts(gl, ["vertex-shader-3d", "fragment-shader-3d"]);
// look up where the vertex data needs to go.
var positionLocation = gl.getAttribLocation(program, "a_position");
var colorLocation = gl.getAttribLocation(program, "a_color");
// lookup uniforms
var matrixLocation = gl.getUniformLocation(program, "u_matrix");
// Create a buffer to put positions in
var positionBuffer = gl.createBuffer();
// Bind it to ARRAY_BUFFER (think of it as ARRAY_BUFFER = positionBuffer)
```
--------------------------------
### Complete GPGPU Example (HTML/JS/CSS)
Source: https://webglfundamentals.org/webgl/lessons/webgl-gpgpu.html
A self-contained example demonstrating WebGL GPGPU, including HTML structure, JavaScript logic, and CSS for presentation.
```html
'use strict';
const vs = `
attribute vec4 position;
void main() {
gl_Position = position;
}
`;
const fs = `
precision highp float;
uniform sampler2D srcTex;
uniform vec2 srcDimensions;
void main() {
vec2 texcoord = gl_FragCoord.xy / srcDimensions;
vec4 value = texture2D(srcTex, texcoord);
gl_FragColor = value * 2.0;
}
`;
const dstWidth = 3;
const dstHeight = 2;
1