My Second WebGL program - Colors!
by Admiral Potato
HTML
<canvas id="gl" width="512" height="384"></canvas>
CSS
#gl{
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
background-color: #555;
background-image: url('http://i.imgur.com/tyJ6j.gif');
}
JavaScript
var canvas = document.getElementById('gl');
var gl = canvas.getContext('experimental-webgl');
var GLScene = function (args) {
var t = this, type = 'GLScene';
if (t.type !== type) {throw type + ' constructor requires use of the `new` keyword';}
t.vertexShader = t.loadShader(0, t.vertexProgram, ['vPosition', 'vColor']);
t.fragmentShader = t.loadShader(1, t.fragmentProgram);
t.shaderList = [t.vertexShader, t.fragmentShader];
t.program = t.createProgramObject(t.shaderList);
if(t.program){
gl.useProgram(t.program);
t.floatsPerVert = 7; //3 floats for pos, 3 floats for color
t.strideLength = t.floatsPerVert * 4; //bytes per float = 4;
t.vertexBuffer = t.createVertexBuffer(t.shapes.square, t.floatsPerVert);
t.resize();
t.render();
} else {
console.log('No valid program!');
}
};
GLScene.prototype = {
type: 'GLScene',
resize: function () {
var t = this;
t.w = gl.canvas.width;
t.h = gl.canvas.height;
gl.viewport(0, 0, t.w, t.h);
gl.clear(gl.COLOR_BUFFER_BIT);
},
render: function () {
var t = this;
gl.clear(gl.COLOR_BUFFER_BIT);
gl.bindBuffer(gl.ARRAY_BUFFER, t.vertexBuffer);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, t.strideLength, 0);
gl.enableVertexAttribArray(0);
//OMGF IT IS SO IMPORTANT TO NOTE THIS: STRIDELENGTH AND OFFSET ARE IN NUMBER OF BYTES!
gl.vertexAttribPointer(1, 4, gl.FLOAT, false, t.strideLength, 12);
gl.enableVertexAttribArray(1);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, t.vertexBuffer.numPoints);
},
shapes: {
square: [
-0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, //colors!
0.5, 0.5, 0.0, 0.0, 1.0, 0.0, 1.0, //colors!
-0.5, -0.5, 0.0, 0.0, 0.0, 1.0, 1.0, //colors!
0.5, -0.5, 0.0, 0.0, 0.0, 0.0, 0.0 //colors!
]
},
createVertexBuffer: function (vertexList,...