Hello, WebGL
A minimal WebGL program
We'll need a <canvas>
HTML element:
const canvas = document.querySelector('#canvas');
const gl = canvas.getContext('webgl2');
if (!gl) { throw "WebGL2 not supported"; }
const program = gl.createProgram();
A program must have at least one vertex shader:
const VERTEX_SHADER = `...`; // see vertex.glsl below
const vertShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertShader, VERTEX_SHADER);
gl.compileShader(vertShader);
and at least one fragment shader:
const FRAGMENT_SHADER = `...`; // see fragment.glsl below
const fragShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragShader, FRAGMENT_SHADER);
Then we attach them to program
and link them:
gl.attachShader(program, vertShader);
gl.attachShader(program, fragShader);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
console.log(gl.getShaderInfoLog(vertShader));
console.log(gl.getShaderInfoLog(fragShader));
}
gl.useProgram(program);
Actually drawing something
Drawing one single huge point:
// vertex.glsl:
#version 300 es
void main() {
gl_Position = vec4(0.0, 0.0, 0.0, 1.0);
gl_PointSize = 80; // pixels
}
// fragment.glsl:
#version 300 es
precision mediump float;
out fragColor vec4;
void main() {
fragColor = vec4(0.0, 1.0, 0.0, 1.0);
}
precision mediump float
is explained in https://www.youtube.com/watch?v=lWLqi3DzaCk.
// all the previous program setup, then
gl.drawArrays(gl.POINTS, 0, 1);
Drawing primitives
gl.drawArrays(gl.POINTS, 0, n_vertices);
gl.drawArrays(gl.LINES, 0, n_vertices);
gl.drawArrays(gl.LINE_LOOP, 0, n_vertices);
gl.drawArrays(gl.TRIANGLES, 0, n_vertices);
...