Skip to content

Instantly share code, notes, and snippets.

@MarkMendell
Created April 13, 2022 22:22
Show Gist options
  • Save MarkMendell/04761142c52f2aa4edacc396cba20505 to your computer and use it in GitHub Desktop.
Save MarkMendell/04761142c52f2aa4edacc396cba20505 to your computer and use it in GitHub Desktop.
<!doctype html>
<div id="root"></div>
<script>
/*
1. Create a WebGL context and add it to the root.
2. Draw a triangle in the WebGL context.
*/
const canvas = document.createElement('canvas');
const root = document.getElementById('root');
root.appendChild(canvas);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const gl = canvas.getContext('webgl');
const vertexShaderSource = `
attribute vec4 a_position;
void main() {
gl_Position = a_position;
}
`;
const fragmentShaderSource = `
precision mediump float;
void main() {
gl_FragColor = vec4(1, 0, 0.5, 1);
}
`;
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexShaderSource);
gl.compileShader(vertexShader);
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentShaderSource);
gl.compileShader(fragmentShader);
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(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);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment