Skip to main content

OpenGL

Khronos: WebGL Specification

I would highly recommend grabbing the Khronos reference card for WebGL, and any other related APIs you might be interested in. This WebGL reference is very useful, but unfortunately it's gated behind a 30-day trial leading to subscription to Scirbd. This is the official source and the only way I know of to get it, and it's not my place to redistribute this material, so here's the official link. I just subscribed with paypal, downloaded my PDFs (all Khronos references), then canceled my account immediately. Scribd might actually be useful if I had more leisure time to read, but I don't so for now it's a hard pass.

WebGL Fundamentals

If you are familiar with OpenGL already, I would recommend starting with drawing a simple texture on 3D geometry. You will see a lot of familiar concepts are used in the JavaScript API when compared to OpenGL in C++.

Within an HTML page, you can wrap JavaScript within <script> tags and directly access OpenGL API and write code similar to what you'd see in C++ using OpenGL. Creating a simple context within a single index.html page would look like this -

<style>
.test {
  background-color: gray;
}
canvas {
  background-color: gray;
  width: 50;
  height: 50;
  display: block;
}
</style>

<!-- 3D Math include for matrix math functions -->
<script src="https://webglfundamentals.org/webgl/resources/m4.js"></script>

<!-- Shader source code -->
<!-- We don't comiple these yet, but this is an example of one way to write your shader code within an HTML document -->
<script id="vertex-shader" type="x-shader/x-vertex">
attribute vec4 a_position;
attribute vec2 a_texcoord;

uniform mat4 u_matrix;

varying vec2 v_texcoord;

void main() {
  // Multiply the position by the matrix.
  gl_Position = u_matrix * a_position;

  // Pass the texcoord to the fragment shader.
  v_texcoord = a_texcoord;
}
</script>
<script id="fragment-shader" type="x-shader/x-vertex">
precision mediump float;

// Passed in from the vertex shader.
varying vec2 v_texcoord;

// The texture.
uniform sampler2D u_texture;

void main() {
  gl_FragColor = texture2D(u_texture, v_texcoord);
}
</script>

<!-- This is all the HTML required to create an OpenGL canvas. The rest will be done in JS -->
<p class="test">This is test HTML with some CSS. Logging with JS...</br>The following block is an OpenGL canvas</p>
<canvas id="canvas"></canvas>

<!-- OpenGL / WebGL context creation -->
<script>
function main() {
  var canvas = document.querySelector("#canvas");
  var gl = canvas.getContext('webgl');
  if (!gl) {
    console.log("ERROR: Unable to get OpenGL context");
    return;
  }
  else {
    console.log("Created OpenGL context on HTML canvas")
  }
}
main();

</script>