Skip to content

Instantly share code, notes, and snippets.

@andy-thomason
Created July 16, 2017 10:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andy-thomason/0c909c157c78cfcacd13120d383b752b to your computer and use it in GitHub Desktop.
Save andy-thomason/0c909c157c78cfcacd13120d383b752b to your computer and use it in GitHub Desktop.
WebGL triangle in 58 lines
<html>
<head>
<script>
function main() {
var canvas = document.getElementById("myGLCanvas");
try {
gl = canvas.getContext("webgl");
} catch(e) {
console.log(e);
}
if (!gl) {
alert("WebGL not available.");
}
gl.clearColor(0.5, 0.5, 0.5, 1);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
source = {
VERTEX_SHADER: "attribute vec3 pos; void main() { gl_Position = vec4(pos, 1); }",
FRAGMENT_SHADER: "void main() { gl_FragColor = vec4(1, 0, 0, 1); }"
}
var shaderProgram = gl.createProgram();
for (i in source) {
shader = gl.createShader(gl[i]);
gl.shaderSource(shader, source[i]);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert("An error occurred compiling the shaders: " + gl.getShaderInfoLog(shader));
return null;
}
gl.attachShader(shaderProgram, shader);
}
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert("Unable to link the shader program.");
}
posIdx = gl.getAttribLocation(shaderProgram, "pos");
pos = [-0.5, -0.5, 0, 0, 0.5, 0, 0.5, -0.5, 0];
posBuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, posBuf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(pos), gl.STATIC_DRAW);
gl.useProgram(shaderProgram);
gl.vertexAttribPointer(posIdx, 3, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(posIdx);
gl.drawArrays(gl.TRIANGLES, 0, 3);
}
</script>
</head>
<body onload="main()">
<canvas id="myGLCanvas" width="500" height="500" style="border: solid">
No HTML5!
</canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment