Drawing a triangle with WebGL

You should see a pink canvas above with a cyan triangle in it. It’s drawn with WebGL. This “hello world” takes around 25 lines, and involves lots of concepts like buffers and shaders.

const canvas = document.getElementById('triangleCanvas');
const gl = canvas.getContext('webgl');

const vertShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertShader, 'attribute vec3 c;void main(void){gl_Position=vec4(c, 1.0);}');
const fragShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragShader, 'void main(void){gl_FragColor=vec4(0,1,1,1);}');
const prog = gl.createProgram();
gl.attachShader(prog, vertShader);
gl.attachShader(prog, fragShader);

gl.clearColor(1, 0, 1, 1);

const vertexBuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ -0.5,0.5,0.0,  -0.5,-0.5,0.0,  0.5,-0.5,0.0 ]), gl.STATIC_DRAW);

const coord = gl.getAttribLocation(prog, "c");
gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0);

gl.drawArrays(gl.TRIANGLES, 0, 3);
Tagged .

Similar posts

More by Jim

👋 I'm Jim, a full-stack product engineer. Want to build an amazing product and a profitable business? Read more about me or Get in touch!

This page copyright James Fisher 2017. Content is not associated with my employer. Found an error? Edit this page.