WebGL rendering fails when using color buffer - javascript

<!doctype html>
<html>
<body>
<canvas id ="ctx" width = "300" height = "300"></canvas>
<script>
//Getting Webgl Context
var ctx = document.getElementById("ctx");
var webgl = ctx.getContext("experimental-webgl");
/*Creating Shader*/
//Vertex Code
var vertexCode =
'attribute vec3 coordinates;'+
'attribute vec3 color;'+
'varying vec3 vColor;'+
'void main(void) {' +
' gl_Position = vec4(coordinates, 1.0);' +
'vColor = color;'+
'}';
//Creating Shader Object
var vertexShader = webgl.createShader(webgl.VERTEX_SHADER);
//Assigning the Source
webgl.shaderSource(vertexShader, vertexCode);
//Compiling the Source
webgl.compileShader(vertexShader);
//Fragment Shader Code
var fragmentCode ='precision mediump float;'+
'varying vec3 vColor;'+
'void main(void) {'+
'gl_FragColor = vec4(vColor, 1.);'+
'}';
//Creating Shader Object
var fragmentShader = webgl.createShader(webgl.FRAGMENT_SHADER);
//Assigning the Source
webgl.shaderSource(fragmentShader, fragmentCode);
//Compiling the Source
webgl.compileShader(fragmentShader);
//Creating Program to store Shader
var shaderProgram = webgl.createProgram();
//Attaching the shaders
webgl.attachShader(shaderProgram, vertexShader);
webgl.attachShader(shaderProgram, fragmentShader);
//linking the Program
webgl.linkProgram(shaderProgram);
//using the Program
webgl.useProgram(shaderProgram);
//Defining geometry
var vertices = [
-0.5,0.5,0.0,
-0.5,-0.5,0.0,
0.5,-0.5,0.0,
0.5,0.5,0.0
];
var colors = [0,0,1, 1,0,0, 0,1,0, 1,0,1,];
indices = [3,2,1,3,1,0];
//Creating a Buffer
var VextexBuffer = webgl.createBuffer();
var IndexBuffer = webgl.createBuffer();
var colorBuffer = webgl.createBuffer();
//Binding the Buffer
webgl.bindBuffer(webgl.ARRAY_BUFFER, VextexBuffer);
webgl.bindBuffer(webgl.ELEMENT_ARRAY_BUFFER, IndexBuffer);
webgl.bindBuffer(webgl.ARRAY_BUFFER, colorBuffer);
//Buffer Data
webgl.bufferData(webgl.ARRAY_BUFFER, new Float32Array(vertices), webgl.STATIC_DRAW);
webgl.bufferData(webgl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), webgl.STATIC_DRAW);
webgl.bufferData(webgl.ARRAY_BUFFER, new Float32Array(colors), webgl.STATIC_DRAW);
/*Associating the shaders to bufferObject*/
//Getting attribute location
var coord = webgl.getAttribLocation(shaderProgram,"coordinates");
var color = webgl.getAttribLocation(shaderProgram, "color");
//pointing an attribute to the currently bound VBO
webgl.vertexAttribPointer(coord, 3, webgl.FLOAT, false ,0,0);
webgl.vertexAttribPointer(color, 3, webgl.FLOAT, false ,0,0);
//enabling the attributes
webgl.enableVertexAttribArray(coord);
webgl.enableVertexAttribArray(color);
//Unbind Array
/*Drawing the Triangle*/
//Clearing the Colour
webgl.clearColor(.5,.5,.5,1);
//Enabling the depth test
webgl.enable(webgl.DEPTH_TEST);
//Clearing colour nuffer bit
webgl.clear(webgl.COLOR_BUFFER_BIT);
//Setting a viewport
webgl.viewport(0,0,ctx.width,ctx.height);
//Draw the triangle
webgl.drawElements(webgl.TRIANGLES,indices.length,webgl.UNSIGNED_SHORT,0);
</script>
</body>
</html>
If I remove colour buffer and everything related to it, the code runs but with colour buffer, I only see gray canvas, nothing else.
Also Chrome console doesn't show any errors or warnings.
Please help me.

Here's the working fiddle.
The biggest mistake in your code is the use of the bindBuffer method. A WebGL context can bind a buffer at a time. Binding two or more buffers at a time results in binding only the last one.
When you have to copy data to a buffer, you need to bind it and then call bufferData function.
Same applies to the vertexAttribPointer function. First bind the buffer you want the attribute to bind to, then call vertexAttribPointer, and so on with the other buffer.
//Getting Webgl Context
var ctx = document.getElementById("ctx");
var webgl = ctx.getContext("experimental-webgl");
/*Creating Shader*/
//Vertex Code
var vertexCode =
'attribute vec3 coordinates;' +
'attribute vec3 color;' +
'varying vec3 vColor;' +
'void main(void) {' +
' gl_Position = vec4(coordinates, 1.0);' +
'vColor = color;' +
'}';
//Creating Shader Object
var vertexShader = webgl.createShader(webgl.VERTEX_SHADER);
//Assigning the Source
webgl.shaderSource(vertexShader, vertexCode);
//Compiling the Source
webgl.compileShader(vertexShader);
//Fragment Shader Code
var fragmentCode = 'precision mediump float;' +
'varying vec3 vColor;' +
'void main(void) {' +
'gl_FragColor = vec4(vColor, 1.);' +
'}';
//Creating Shader Object
var fragmentShader = webgl.createShader(webgl.FRAGMENT_SHADER);
//Assigning the Source
webgl.shaderSource(fragmentShader, fragmentCode);
//Compiling the Source
webgl.compileShader(fragmentShader);
//Creating Program to store Shader
var shaderProgram = webgl.createProgram();
//Attaching the shaders
webgl.attachShader(shaderProgram, vertexShader);
webgl.attachShader(shaderProgram, fragmentShader);
//linking the Program
webgl.linkProgram(shaderProgram);
//using the Program
webgl.useProgram(shaderProgram);
//Defining geometry
var vertices = [
-0.5, 0.5, 0.0,
-0.5, -0.5, 0.0,
0.5, -0.5, 0.0,
0.5, 0.5, 0.0
];
var colors = [0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, ];
indices = [3, 2, 1, 3, 1, 0];
var coord = webgl.getAttribLocation(shaderProgram, "coordinates");
var color = webgl.getAttribLocation(shaderProgram, "color");
webgl.enableVertexAttribArray(coord);
webgl.enableVertexAttribArray(color);
//Creating a Buffer
var VextexBuffer = webgl.createBuffer();
var IndexBuffer = webgl.createBuffer();
var colorBuffer = webgl.createBuffer();
//Binding the Buffer
webgl.bindBuffer(webgl.ARRAY_BUFFER, VextexBuffer);
webgl.bufferData(webgl.ARRAY_BUFFER, new Float32Array(vertices), webgl.STATIC_DRAW);
webgl.bindBuffer(webgl.ELEMENT_ARRAY_BUFFER, IndexBuffer);
webgl.bufferData(webgl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), webgl.STATIC_DRAW);
webgl.bindBuffer(webgl.ARRAY_BUFFER, colorBuffer);
webgl.bufferData(webgl.ARRAY_BUFFER, new Float32Array(colors), webgl.STATIC_DRAW);
webgl.bindBuffer(webgl.ARRAY_BUFFER, VextexBuffer);
webgl.vertexAttribPointer(coord, 3, webgl.FLOAT, false, 0, 0);
webgl.bindBuffer(webgl.ARRAY_BUFFER, colorBuffer);
webgl.vertexAttribPointer(color, 3, webgl.FLOAT, false, 0, 0);
/*Drawing the Triangle*/
//Clearing the Colour
webgl.clearColor(.5, .5, .5, 1);
//Enabling the depth test
webgl.enable(webgl.DEPTH_TEST);
//Clearing colour nuffer bit
webgl.clear(webgl.COLOR_BUFFER_BIT);
//Setting a viewport
webgl.viewport(0, 0, ctx.width, ctx.height);
//Draw the triangle
webgl.drawElements(webgl.TRIANGLES, indices.length, webgl.UNSIGNED_SHORT, 0);
<canvas id ="ctx" width = "300" height = "300"></canvas>

You're overwriting your vertex positions with your colors:
webgl.bufferData(webgl.ARRAY_BUFFER, new Float32Array(vertices), webgl.STATIC_DRAW);
webgl.bufferData(webgl.ARRAY_BUFFER, new Float32Array(colors), webgl.STATIC_DRAW);
At any given time there can only be one buffer bound for each type (ARRAY_BUFFER and ELEMENT_ARRAY_BUFFER), so
the flow is to bind a buffer and set its data followed by setting up the vertex attribute pointers for that specific buffer, then proceed to the next buffer:
// setup positions
var VextexBuffer = webgl.createBuffer();
webgl.bindBuffer(webgl.ARRAY_BUFFER, VextexBuffer);
webgl.bufferData(webgl.ARRAY_BUFFER, new Float32Array(vertices), webgl.STATIC_DRAW);
var coord = webgl.getAttribLocation(shaderProgram,"coordinates");
webgl.vertexAttribPointer(coord, 3, webgl.FLOAT, false ,0,0);
// setup indices
var IndexBuffer = webgl.createBuffer();
webgl.bindBuffer(webgl.ELEMENT_ARRAY_BUFFER, IndexBuffer);
webgl.bufferData(webgl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), webgl.STATIC_DRAW);
// setup colors
var colorBuffer = webgl.createBuffer();
webgl.bindBuffer(webgl.ARRAY_BUFFER, colorBuffer);
webgl.bufferData(webgl.ARRAY_BUFFER, new Float32Array(colors), webgl.STATIC_DRAW);
var color = webgl.getAttribLocation(shaderProgram, "color");
webgl.vertexAttribPointer(color, 3, webgl.FLOAT, false ,0,0);
For applications that work with multiple different buffers and intend to be realtime the flow is to create and set the buffers during initialization phase to then only bind the buffer and set the vertex attribute pointers during the animation loop.
<!doctype html>
<html>
<body>
<canvas id ="ctx" width = "300" height = "300"></canvas>
<script>
//Getting Webgl Context
var ctx = document.getElementById("ctx");
var webgl = ctx.getContext("experimental-webgl");
/*Creating Shader*/
//Vertex Code
var vertexCode =
'attribute vec3 coordinates;'+
'attribute vec3 color;'+
'varying vec3 vColor;'+
'void main(void) {' +
' gl_Position = vec4(coordinates, 1.0);' +
'vColor = color;'+
'}';
//Creating Shader Object
var vertexShader = webgl.createShader(webgl.VERTEX_SHADER);
//Assigning the Source
webgl.shaderSource(vertexShader, vertexCode);
//Compiling the Source
webgl.compileShader(vertexShader);
//Fragment Shader Code
var fragmentCode ='precision mediump float;'+
'varying vec3 vColor;'+
'void main(void) {'+
'gl_FragColor = vec4(vColor, 1.);'+
'}';
//Creating Shader Object
var fragmentShader = webgl.createShader(webgl.FRAGMENT_SHADER);
//Assigning the Source
webgl.shaderSource(fragmentShader, fragmentCode);
//Compiling the Source
webgl.compileShader(fragmentShader);
//Creating Program to store Shader
var shaderProgram = webgl.createProgram();
//Attaching the shaders
webgl.attachShader(shaderProgram, vertexShader);
webgl.attachShader(shaderProgram, fragmentShader);
//linking the Program
webgl.linkProgram(shaderProgram);
//using the Program
webgl.useProgram(shaderProgram);
//Defining geometry
var vertices = [
-0.5,0.5,0.0,
-0.5,-0.5,0.0,
0.5,-0.5,0.0,
0.5,0.5,0.0
];
var colors = [0,0,1, 1,0,0, 0,1,0, 1,0,1,];
indices = [3,2,1,3,1,0];
// setup positions
var VextexBuffer = webgl.createBuffer();
webgl.bindBuffer(webgl.ARRAY_BUFFER, VextexBuffer);
webgl.bufferData(webgl.ARRAY_BUFFER, new Float32Array(vertices), webgl.STATIC_DRAW);
var coord = webgl.getAttribLocation(shaderProgram,"coordinates");
webgl.vertexAttribPointer(coord, 3, webgl.FLOAT, false ,0,0);
// setup indices
var IndexBuffer = webgl.createBuffer();
webgl.bindBuffer(webgl.ELEMENT_ARRAY_BUFFER, IndexBuffer);
webgl.bufferData(webgl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), webgl.STATIC_DRAW);
// setup colors
var colorBuffer = webgl.createBuffer();
webgl.bindBuffer(webgl.ARRAY_BUFFER, colorBuffer);
webgl.bufferData(webgl.ARRAY_BUFFER, new Float32Array(colors), webgl.STATIC_DRAW);
var color = webgl.getAttribLocation(shaderProgram, "color");
webgl.vertexAttribPointer(color, 3, webgl.FLOAT, false ,0,0);
//enabling the attributes
webgl.enableVertexAttribArray(coord);
webgl.enableVertexAttribArray(color);
//Unbind Array
/*Drawing the Triangle*/
//Clearing the Colour
webgl.clearColor(.5,.5,.5,1);
//Enabling the depth test
webgl.enable(webgl.DEPTH_TEST);
//Clearing colour nuffer bit
webgl.clear(webgl.COLOR_BUFFER_BIT);
//Setting a viewport
webgl.viewport(0,0,ctx.width,ctx.height);
//Draw the triangle
webgl.drawElements(webgl.TRIANGLES,indices.length,webgl.UNSIGNED_SHORT,0);
</script>
</body>
</html>

Related

WebGL Recreate Overlapping Triangles

I'm trying to create a program without css that displays several overlapping triangles on a black background. Once I can get the triangles to display (like in the picture attached only with different colors), I need to implement either a z-buffer or a painter's algorithm; but first, I can't figure out what's wrong in the code below that they aren't displaying at all. I think it's an issue with my shaders perhaps?
<!doctype html>
<html>
<body>
<canvas width = "500" height = "500" id = "canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
gl = canvas.getContext('webgl');
var positions = [
0, 1, -1, -1, 1, -1,
-1, -1, -0, -1, -1, -0.5,
1, -1, 0, -1, 1, -0.5,
1, 1, 0, 1, 1, -1,
-1, 1, -1, 0, -0, 1
];
var colors = [
1,0,1, 1,0,1, 1,0,1, 1,0,1,//purple
0,0,1, 0,0,1, 0,0,1, 0,0,1,//blue
1,1,0, 1,1,0, 1,1,0, 1,1,0,//yellow
1,0,0, 1,0,0, 1,0,0, 1,0,0,//red
0,1,0, 0,1,0, 0,1,0, 0,1,0, //green
];
//vertex buffer
var vbuffer = gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, vbuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
//color buffer
var cbuffer = gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, cbuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
//shaders
var vCode =
`
attribute vec2 a_Position;
attribute vec3 a_Color;
varying vec3 v_Color;
void main()
{
gl_Position = vec4(a_Position, 0.0, 1.0);
v_Color = a_Color;
}`;
var fragCode =
`
precision mediump float;
varying vec3 v_Color;
void main()
{
gl_FragColor = vec4(v_Color, 1.0);
}`;
//vertex shader
var vShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vShader, vCode);
gl.compileShader(vShader);
//fragment shader
var fShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fShader, fragCode);
gl.compileShader(fShader);
var shaders = gl.createProgram();
gl.attachShader(shaders, vShader);
gl.attachShader(shaders, fShader);
gl.linkProgram(shaders);
//vertex buffer
gl.bindBuffer(gl.ARRAY_BUFFER, vbuffer);
var _position = gl.getAttribLocation(shaders, "position");
gl.vertexAttribPointer(_position, 3, gl.FLOAT, false,0,0);
gl.enableVertexAttribArray(_position);
//color buffer
gl.bindBuffer(gl.ARRAY_BUFFER, cbuffer);
var _color = gl.getAttribLocation(shaders, "color");
gl.vertexAttribPointer(_color, 3, gl.FLOAT, false,0,0) ;
gl.enableVertexAttribArray(_color);
gl.useProgram(shaders);
//depth testing
gl.disable(gl.DEPTH_TEST);
gl.enable(gl.BLEND);
gl.depthMask(gl.FALSE);
//clears buffer
gl.clearColor(0.5, 0.5, 0.5, 0.9);
gl.clearDepth(1.0);
gl.viewport(0.0, 0.0, canvas.width, canvas.height);
gl.clear(gl.cbuffer_BIT | gl.DEPTH_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, 15);
</script>
</body>
</html>
There are four mistakes in the code. I corrected the mistakes and added explanations. Here is the working code:
<!doctype html>
<html>
<body>
<canvas width = "500" height = "500" id = "canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
gl = canvas.getContext('webgl');
var positions = [
0, 1, -1, -1, 1, -1,
-1, -1, -0, -1, -1, -0.5,
1, -1, 0, -1, 1, -0.5,
1, 1, 0, 1, 1, -1,
-1, 1, -1, 0, -0, 1
];
/*var colors = [
1,0,1, 1,0,1, 1,0,1, 1,0,1,//purple
0,0,1, 0,0,1, 0,0,1, 0,0,1,//blue
1,1,0, 1,1,0, 1,1,0, 1,1,0,//yellow
1,0,0, 1,0,0, 1,0,0, 1,0,0,//red
0,1,0, 0,1,0, 0,1,0, 0,1,0, //green
];
BUG 1: Color array should be 3 values per vertex. This code assumes 4 values are used
*/
var colors = [
1,0,1, 1,0,1, 1,0,1, //purple
0,0,1, 0,0,1, 0,0,1, //blue
1,1,0, 1,1,0, 1,1,0, //yellow
1,0,0, 1,0,0, 1,0,0, //red
0,1,0, 0,1,0, 0,1,0 //green
];
//vertex buffer
var vbuffer = gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, vbuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
//color buffer
var cbuffer = gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, cbuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
//shaders
var vCode =
`
attribute vec2 a_Position;
attribute vec3 a_Color;
varying vec3 v_Color;
void main()
{
gl_Position = vec4(a_Position, 0.0, 1.0);
v_Color = a_Color;
}`;
var fragCode =
`
precision mediump float;
varying vec3 v_Color;
void main()
{
gl_FragColor = vec4(v_Color, 1.0);
}`;
//vertex shader
var vShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vShader, vCode);
gl.compileShader(vShader);
//fragment shader
var fShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fShader, fragCode);
gl.compileShader(fShader);
var shaders = gl.createProgram();
gl.attachShader(shaders, vShader);
gl.attachShader(shaders, fShader);
gl.linkProgram(shaders);
//vertex buffer
gl.bindBuffer(gl.ARRAY_BUFFER, vbuffer);
//var _position = gl.getAttribLocation(shaders, "position"); BUG 2: attribute name is "a_Position"
var _position = gl.getAttribLocation(shaders, "a_Position");
//gl.vertexAttribPointer(_position, 3, gl.FLOAT, false,0,0); BUG 3: a_Position is a vec2. It only accepts 2 values.
gl.vertexAttribPointer(_position, 2, gl.FLOAT, false,0,0);
gl.enableVertexAttribArray(_position);
//color buffer
gl.bindBuffer(gl.ARRAY_BUFFER, cbuffer);
//var _color = gl.getAttribLocation(shaders, "color"); BUG 4: attribute name is "a_Color"
var _color = gl.getAttribLocation(shaders, "a_Color");
gl.vertexAttribPointer(_color, 3, gl.FLOAT, false,0,0) ;
gl.enableVertexAttribArray(_color);
gl.useProgram(shaders);
//depth testing
gl.disable(gl.DEPTH_TEST);
gl.enable(gl.BLEND);
gl.depthMask(gl.FALSE);
//clears buffer
gl.clearColor(0.5, 0.5, 0.5, 0.9);
gl.clearDepth(1.0);
gl.viewport(0.0, 0.0, canvas.width, canvas.height);
gl.clear(gl.cbuffer_BIT | gl.DEPTH_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, 15);
</script>
</body>
</html>

Why am i getting "out is null" (glmatrix) error? Webgl

The goal is a textured open cylinder. I believe the issue is with the setCamera() function. I havent made any changes from when I used the function as it is previously. Running on an http-server localhost in firefox(javascript is enabled). I would really appreciate a solution on how to make this work as well as any tips.
"glmatrix" is a Javascript Matrix and Vector library.
Here is the code:
var mat4 = glMatrix.mat4;
var segments = 64;
var cylVertices=[]; //sidevertices
var positionAttribLocation = null;
var gl = null;
var program = null;
var cylVertexBufferObject = null;
var matWorldUniformLocation =null;
var matViewUniformLocation =null;
var matProjectionUniformLocation =null;
var worldMatrix = null;
var viewMatrix = null;
var projectionMatrix = null;
var canvas = null;
var vertexShaderText =
[
'precision mediump float;',
'',
'attribute vec3 vertPosition;',
'attribute vec2 vertTexCoord;',
'varying vec2 fragTexCoord;',
'uniform mat4 mWorld;',
'uniform mat4 mView;',
'uniform mat4 mProjection;',
'',
'void main()',
'{',
' fragTexCoord = vertTexCoord;',
' gl_Position = mProjection * mView * mWorld * vec4(vertPosition, 1.0);',
'}'
].join('\n');
var fragmentTexShaderText =
[
'precision mediump float;',
'',
'varying vec2 fragTexCoord;',
'uniform sampler2D sampler;',
'void main()',
'{',
' gl_FragColor = texture2D(sampler,fragTexCoord);',
'}'
].join('\n');
var initDemo = function () {
console.log('This is working');
canvas = document.getElementById('game-surface');
gl = canvas.getContext('webgl');
if (!gl) {
console.log('WebGL not supported, falling back on experimental-webgl');
gl = canvas.getContext('experimental-webgl');
}
if (!gl) {
alert('Your browser does not support WebGL');
}
clear();
gl.enable(gl.DEPTH_TEST);//enable drawing over if closer to the virtual camera
//
//Create Shaders
//
var vertexShader = gl.createShader(gl.VERTEX_SHADER);
var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(vertexShader,vertexShaderText);
gl.shaderSource(fragmentShader,fragmentTexShaderText);
gl.compileShader(vertexShader);
if (!gl.getShaderParameter(vertexShader,gl.COMPILE_STATUS)){
console.error('ERROR compiling vertex shader!', gl.getShaderInfoLog(vertexShader));
return;
}
gl.compileShader(fragmentShader);
if (!gl.getShaderParameter(fragmentShader,gl.COMPILE_STATUS)){
console.error('ERROR compiling fragment shader!', gl.getShaderInfoLog(fragmentShader));
return;
}
program = gl.createProgram();
gl.attachShader(program,vertexShader);
gl.attachShader(program,fragmentShader)
gl.linkProgram(program);
if (!gl.getProgramParameter(program,gl.LINK_STATUS)){
console.error('ERROR linking program!', gl.getProgramInfoLog(program));
return;
}
a=0, b=0, y=0, u=0, v=0, s=0, t=0; //The origin
r=1.0,g=0.4,b=0.6;
theta = (Math.PI/180) * (360);
//theta = (Math.PI/180) * (360/(segments)); //Degrees = radians * (180 / )
for (i =0;i<=(segments);i++){
x = i*Math.cos(theta);
z = i*Math.sin(theta);
s=(theta+180)/360;
cylVertices.push(x, y, z, s,0); //Sidevertices along the bottom
cylVertices.push(x, y+2, z, s,2); //Sidevertices along the top
}
cylArray = new Float32Array(cylVertices); //sidearray
//
//------MAIN RENDER LOOP-------
//
var angle = 0;
var loop = function (){
setCamera();
angle = performance.now() / 1000 / 6 * 2 * Math.PI;
mat4.rotate(xRotationMatrix,identityMatrix, angle, [0,1,0]);//x rotation
gl.uniformMatrix4fv(matWorldUniformLocation, gl.FALSE, xRotationMatrix);
clear();
theVertexBufferObject = gl.createBuffer();
drawCylSide();
requestAnimationFrame(loop);
};
requestAnimationFrame(loop);
};
//
// --------------------functions--------------------
//
function drawCylSide(){
gl.bindBuffer(gl.ARRAY_BUFFER,theVertexBufferObject);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(cylArray),gl.STATIC_DRAW);
setPointer(5);
var texCoordAttribLocation = gl.getAttribLocation(program,'vertTexCoord');
gl.vertexAttribPointer(
texCoordAttribLocation, //Attribute location
2, //Number of vertix elements
gl.FLOAT, //Type of elements
gl.FALSE, //Normalised
5 * Float32Array.BYTES_PER_ELEMENT, //Size of individual vertex
3 * Float32Array.BYTES_PER_ELEMENT, //Offset
);
gl.enableVertexAttribArray(positionAttribLocation);
gl.enableVertexAttribArray(texCoordAttribLocation);
var boxTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, boxTexture);
gl.texParameter(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);
gl.texParameter(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);
gl.texParameter(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER,gl.LINEAR);
gl.texParameter(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER,gl.LINEAR);
gl.texImage2D(
gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA,
gl.UNSIGNED_BYTE,
document.getElementById('wall-img')
);
gl.bindTexture(gl.TEXTURE_2D, null);
gl.useProgram(program);
gl.bindTexture(gl.TEXTURE_2D, boxTexture);
gl.activeTexture(gl.TEXTURE0);
gl.drawArrays(gl.TRIANGLE_STRIP,0, segments);
};
function setPointer(n){
positionAttribLocation = gl.getAttribLocation(program,'vertPosition');
gl.vertexAttribPointer(
positionAttribLocation, //Attribute location
3, //Number of vertix elements
gl.FLOAT, //Type of elements
gl.FALSE, //Normalised
n * Float32Array.BYTES_PER_ELEMENT, //Size of individual vertex
0 //Offset
);
};
function clear(){
gl.clearColor(0.75, 0.85, 0.8, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
};
function setCamera(){
mat4.identity(worldMatrix);
mat4.lookAt(viewMatrix,[0,1,-8],[0,0,0],[0,10,0]);
mat4.perspective(projectionMatrix,glMatrix.glMatrix.toRadian(45),canvas.width/canvas.height,0.1,1000.0);
gl.uniformMatrix4fv(matWorldUniformLocation,gl.FALSE,worldMatrix);
gl.uniformMatrix4fv(matViewUniformLocation,gl.FALSE,viewMatrix);
gl.uniformMatrix4fv(matProjectionUniformLocation,gl.FALSE,projectionMatrix);
};
You need to initialize vectors and matrices using the respective create function of glMatrix.
var worldMatrix = mat4.create();
var viewMatrix = mat4.create();
var projectionMatrix = mat4.create();

WebGL "draw a square" program, need help debugging it

I am following the LearningWebGL tutorials, I am not able to reproduce the first code itself. Here is the buggy code :
var modelView = mat4.create()
var projection = mat4.create()
var vertexPositionPointer, modelViewMatrixPointer, projectionMatrixPointer
var vertexBuffer
var vertices =
[
0.5, 0.5, 0.0,
-0.5, 0.5, 0.0,
0.5, -0.5, 0.0,
-0.5, -0.5, 0.0
]
var vertexShaderSource =
"attribute vec3 vertexPosition;"+ "\n" +
"uniform mat4 modelView;"+ "\n" +
"uniform mat4 projection;"+ "\n" +
"void main(){"+ "\n" +
"gl_Position = projection * modelView * vec4(vertexPosition, 1.0);"+ "\n" +
"}";
var fragmentShaderSource =
"void main(){"+ "\n" +
"gl_FragColor = vec4(1.0, 0, 0, 1.0);"+ "\n" +
"}";
function setup(){
var canvas = document.getElementById('canvas')
var gl = canvas.getContext("webgl", {antialias : false})
gl.viewport(0, 0, canvas.clientWidth, canvas.clientHeight)
var vertexShader = getShader(gl, gl.VERTEX_SHADER, vertexShaderSource)
var fragmentShader = getShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource)
var program = gl.createProgram()
gl.attachShader(program, vertexShader)
gl.attachShader(program, fragmentShader)
gl.linkProgram(program)
gl.useProgram(program)
vertexPositionPointer = gl.getAttribLocation(program, "vertexPosition")
gl.enableVertexAttribArray(vertexPositionPointer)
modelViewMatrixPointer = gl.getUniformLocation(program, "modelView")
projectionMatrixPointer = gl.getUniformLocation(program, "projection")
vertexBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW)
gl.vertexAttribPointer(vertexPositionPointer, 3, gl.FLOAT, gl.FALSE, 0, 0)
gl.clearColor(0, 0, 0, 1)
gl.clear(gl.COLOR_BUFFER_BIT)
mat4.translate(modelView, modelView, [0, 0, -1.4])
mat4.perspective(projection, Math.PI/3.5, canvas.clientWidth/canvas.clientHeight, 1, 1000)
gl.uniformMatrix4fv(modelViewMatrixPointer, false, modelView)
gl.uniformMatrix4fv(projectionMatrixPointer, false, projection)
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
}
function getShader(gl, type, source){
var shader = gl.createShader(type)
gl.shaderSource(shader, source)
gl.compileShader(shader)
console.log(gl.getShaderParameter(shader, gl.COMPILE_STATUS))
console.log(gl.getShaderInfoLog(shader))
return shader;
}
setup()
<script src="https://rawgit.com/toji/gl-matrix/master/dist/gl-matrix.js"></script>
<canvas id="canvas" style="border: none;"></canvas>
The above code produces :
Even though the z-translate value is set to -1, the entire canvas is painted red which too is incorrect.
What have I done wrong ?....
(some dummy text so that my word count increases and the post gets passed...)

Single color from javascript to fragment shader

I'm trying to generate a random color everytime the code executes and passing it to the fragment shader(to draw a triangle).
Reading other posts, I've decided that the most effective solutions seems to be:
set a uniform variable in the fragment shader
link it to a javascript variable
write to the fragment shader with uniform4f providing the data
Trying to structure this, my snippet doesn't display the triangle but only the background. If I take
away all the lines that deal with the color, the triangle appears again.
var can = document.getElementById('cont');
var gl = can.getContext('experimental-webgl');
gl.clearColor(0.0, 0.1, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
red = Math.random();
green = Math.random();
blue = Math.random();
alpha = Math.random();
var vertices = [-1,-1,1,-1,0,0.5];
var colorData = [red,green,blue,alpha];
//Create color buffer
var cbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER,cbo);
gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(colorData),gl.STATIC_DRAW);
//Create vertex buffer
var vbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER,vbo);
gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(vertices),gl.STATIC_DRAW);
//Shaders
var vshaderCode = 'attribute vec2 pos;' + 'void main() {gl_Position = vec4 (pos,0.,1.);}';
var fshaderCode = 'precision mediump float;' + 'uniform vec4 uColor' + 'void main() {gl_FragColor = uColor;}';
function getShader(shaderSource,type) {
var shad = gl.createShader(type);
gl.shaderSource(shad,shaderSource);
gl.compileShader(shad);
return shad;
}
var vertexShader = getShader (vshaderCode,gl.VERTEX_SHADER);
var fragmentShader = getShader (fshaderCode,gl.FRAGMENT_SHADER);
//Create the program to link shaders
var prog = gl.createProgram();
gl.attachShader(prog,vertexShader);
gl.attachShader(prog,fragmentShader);
gl.linkProgram(prog);
var _position = gl.getAttribLocation(prog, "pos");
var u_ColorLocation = gl.getUniformLocation(prog, "uColor");
//Draw
gl.enableVertexAttribArray(_position);
gl.useProgram(prog);
gl.vertexAttribPointer(_position, 2, gl.FLOAT, false, 0,0);
gl.uniform4f(u_ColorLocation, colorData);
gl.drawArrays(gl.TRIANGLES, 0, 3);
The console says that gl.uniform4f(u_ColorLocation, colorData); wants five arguments. That point is not clear to me.
Even if I change that line to something like gl.uniform4f(u_colorLocation, 0, 0, 1, 1); the program doesn't link.
How do I pass then my values from javascript to the fragment on the gpu so that my triangle has only one color, driven by javascript variables?
You were missing a ; on your fshaderCode shader so it wasn't compiling.
Reading the COMPILE_STATUS of the shader can help you work out if your have any syntax problems.
if (!gl.getShaderParameter(shad, gl.COMPILE_STATUS)) {
console.log("COMPILE_STATUS", gl.getShaderInfoLog(shad));
}
Updated code to show random colour triangle
var can = document.getElementById('cont');
var gl = can.getContext('experimental-webgl');
gl.clearColor(0.0, 0.1, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
red = Math.random();
green = Math.random();
blue = Math.random();
alpha = Math.random();
var vertices = [-1,-1,1,-1,0,0.5];
var colorData = [red,green,blue,alpha];
//Create color buffer
var cbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER,cbo);
gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(colorData),gl.STATIC_DRAW);
//Create vertex buffer
var vbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER,vbo);
gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(vertices),gl.STATIC_DRAW);
//Shaders
var vshaderCode = 'attribute vec2 pos;' + 'void main()' + '{gl_Position = vec4 (pos,0.,1.);' + '}';
var fshaderCode = 'precision mediump float;' + 'uniform vec4 uColor;' + 'void main() {gl_FragColor = uColor;}';
function getShader(shaderSource,type) {
var shad = gl.createShader(type);
gl.shaderSource(shad,shaderSource);
gl.compileShader(shad);
if (!gl.getShaderParameter(shad, gl.COMPILE_STATUS)) {
console.log("COMPILE_STATUS", gl.getShaderInfoLog(shad));
}
return shad;
}
var vertexShader = getShader (vshaderCode,gl.VERTEX_SHADER);
var fragmentShader = getShader (fshaderCode,gl.FRAGMENT_SHADER);
//Create the program to link shaders
var prog = gl.createProgram();
gl.attachShader(prog,vertexShader);
gl.attachShader(prog,fragmentShader);
gl.linkProgram(prog);
var _position = gl.getAttribLocation(prog, "pos");
var u_ColorLocation = gl.getUniformLocation(prog, "uColor");
//Draw
var r = Math.random(), g= Math.random(), b = Math.random();
gl.enableVertexAttribArray(_position);
gl.useProgram(prog);
gl.vertexAttribPointer(_position, 2, gl.FLOAT, false, 0,0);
gl.uniform4f(u_ColorLocation, r, g, b, 1.0);
gl.drawArrays(gl.TRIANGLES, 0, 3);
<canvas id="cont"></canvas>
In your fragmentshader you're missing a colon behind your uniform declaration:
var fshaderCode = 'precision mediump float;' + 'uniform vec4 uColor;' + 'void main() {gl_FragColor = uColor;}';
As mentioned in the answer below checking the compile status is helpful here, as writing shaders in its own files is.
As to setting uniforms there are uniformXX(ie. uniform4f) and uniformXXv(ie. uniform4fv) variants. the v stands for vector and needs to be used when you provide a vector of data like your color.
So you want to change this to uniform4fv too.
var can = document.getElementById('cont');
var gl = can.getContext('experimental-webgl');
gl.clearColor(0.0, 0.1, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
red = Math.random();
green = Math.random();
blue = Math.random();
alpha = Math.random();
var vertices = [-1,-1,1,-1,0,0.5];
var colorData = [red,green,blue,alpha];
//Create color buffer
var cbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER,cbo);
gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(colorData),gl.STATIC_DRAW);
//Create vertex buffer
var vbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER,vbo);
gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(vertices),gl.STATIC_DRAW);
//Shaders
var vshaderCode = 'attribute vec2 pos;' + 'void main() {gl_Position = vec4 (pos,0.,1.);}';
var fshaderCode = 'precision mediump float;' + 'uniform vec4 uColor;' + 'void main() {gl_FragColor = uColor;}';
function getShader(shaderSource,type) {
var shad = gl.createShader(type);
gl.shaderSource(shad,shaderSource);
gl.compileShader(shad);
return shad;
}
var vertexShader = getShader (vshaderCode,gl.VERTEX_SHADER);
var fragmentShader = getShader (fshaderCode,gl.FRAGMENT_SHADER);
//Create the program to link shaders
var prog = gl.createProgram();
gl.attachShader(prog,vertexShader);
gl.attachShader(prog,fragmentShader);
gl.linkProgram(prog);
var _position = gl.getAttribLocation(prog, "pos");
var u_ColorLocation = gl.getUniformLocation(prog, "uColor");
//Draw
gl.enableVertexAttribArray(_position);
gl.useProgram(prog);
gl.vertexAttribPointer(_position, 2, gl.FLOAT, false, 0,0);
gl.uniform4fv(u_ColorLocation, colorData);
gl.drawArrays(gl.TRIANGLES, 0, 3);
<canvas id="cont"></canvas>

WebGL draw loop and translation

I'm want my javascript program to be shifting a triangle to the right.
What I'm focusing on right now are matrices and draw loops. I've never done such a thing so I may be off road but what I'm attempting to do, for study purposes is this:
-Setup the webgl pipeline so I display correctly a triangle (OK)
-Write a function with a matrix that allows me to pass in the values of translation (seems ok but I'm not sure)
var translation_prototype = [1,0,0,0,
0,1,0,0,
0,0,1,0,
tx,ty,0,1];
Leaving out for the moment rotation a scaling and modelview, since I'm perfectly happy(just for the sake of an exercise) with the orthographic view webgl provides.
-Setup a loop that cycles through the drawArrays (even here I'm not sure if the loop starts and ends in the correct place)
I suspect I'm really close, but the triangle doesn't move (tx remains constant).
Here's the code(I think I don't even need to clear the color and depth buffer since I'm only translating on x axis)
<!DOCTYPE HTML>
<html>
<canvas id = "can" width="400" height="400">
</canvas>
<script>
var webgl_canvas = document.getElementById('can');
var gl = webgl_canvas.getContext('experimental-webgl');
var triangles = [-0.8,-0.8,0,0.8,-0.8,0,0,0.8,0];
var vertexBuffer = gl.createBuffer();
var tx = 0.1;
var ty = 0;
var translation_prototype = [1,0,0,0,
0,1,0,0,
0,0,1,0,
tx,ty,0,1];
var vertexShader_source = 'attribute vec3 a_position;' + 'uniform vec4 u_translation;' + 'void main() { gl_Position = u_translation * vec4 (a_position,1);}';
var fragmentShader_source = 'precision mediump float;' + 'void main() { gl_FragColor = vec4 (0.9,0,0.1,1); }';
function getTimeInSeconds () {
return Date.now() * 0.001;
}
function makeTranslation (tx, ty) {
return translation_prototype;
}
//Compile shaders
var buildShader = function (shaderSource, typeOfShader) {
var shader = gl.createShader(typeOfShader);
gl.shaderSource(shader, shaderSource);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert (gl.getShaderInfoLog(shader));
}
return shader;
}
var compiledVertexShader = buildShader (vertexShader_source, gl.VERTEX_SHADER);
var compiledFragmentShader = buildShader (fragmentShader_source, gl.FRAGMENT_SHADER);
//setup GLSL program
program = gl.createProgram();
gl.attachShader(program,compiledVertexShader);
gl.attachShader(program,compiledFragmentShader);
gl.linkProgram(program);
//Fill the buffer with vertex data
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(triangles), gl.STATIC_DRAW);
vertexBuffer.itemSize = 3;
vertexBuffer.numItems = 3;
gl.clear(gl.COLOR_BUFFER_BIT);
var positionLocation = gl.getAttribLocation(program,"a_position");
gl.enableVertexAttribArray(positionLocation);
gl.useProgram(program);
var shaderTranlsationMatrix = gl.getUniformLocation(program, "u_translation");
gl.uniformMatrix4fv(shaderTranlsationMatrix,false,new Float32Array(translation_prototype));
gl.vertexAttribPointer(positionLocation, vertexBuffer.itemSize, gl.FLOAT, false, 0, 0);
var startTime = 0;
function animate (time) {
//Draw loop
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
var deltaTime = (time - startTime);
makeTranslation((tx*deltaTime),(ty*deltaTime));
console.log(tx,ty,deltaTime);
gl.drawArrays (gl.TRIANGLES, 0, vertexBuffer.numItems);
startTime = time;
window.requestAnimationFrame(animate);
}
animate(0);
</script>
</html>
<!-- start last edited snippet -->
<!DOCTYPE HTML>
<html>
<canvas id = "can" width="400" height="400">
</canvas>
<script>
var webgl_canvas = document.getElementById('can');
var gl = webgl_canvas.getContext('experimental-webgl');
var vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,0,1,-1,0,0,1,0]), gl.STATIC_DRAW);
vertexBuffer.itemSize = 3;
vertexBuffer.numItems = 3;
var identityMatrix = [1,0,0,0,
0,1,0,0,
0,0,1,0,
0,0,0,1];
function translation (tx,ty,tz) {
return [1,0,0,0,
0,1,0,0,
0,0,1,0,
tx,ty,tz,1]
}
var vertexShader_source = 'attribute vec3 a_position;' + 'uniform mat4 u_move;' + 'void main() { gl_Position = u_move * vec4 (a_position,1); }';
var fragmentShader_source = 'precision mediump float;' + 'void main() { gl_FragColor = vec4 (0.9,0,0.1,1); }';
//Compile shaders
var buildShader = function (shaderSource, typeOfShader) {
var shader = gl.createShader(typeOfShader);
gl.shaderSource(shader, shaderSource);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert (gl.getShaderInfoLog(shader));
}
return shader;
}
var compiledVertexShader = buildShader (vertexShader_source, gl.VERTEX_SHADER);
var compiledFragmentShader = buildShader (fragmentShader_source, gl.FRAGMENT_SHADER);
//setup GLSL program
program = gl.createProgram();
gl.attachShader(program,compiledVertexShader);
gl.attachShader(program,compiledFragmentShader);
gl.linkProgram(program);
var positionLocation = gl.getAttribLocation(program,"a_position");
gl.enableVertexAttribArray(positionLocation);
gl.useProgram(program);
var tx = 0, ty = 0, tz = 0;
var translate = gl.getUniformLocation (program, "u_move");
gl.uniformMatrix4fv(translate,false,new Float32Array(identityMatrix));
gl.vertexAttribPointer(positionLocation, vertexBuffer.itemSize, gl.FLOAT, false, 0, 0);
//Draw
var start_time =0;
var animate=function(time) {
var dt= time-start_time;
tx+=0.5;
translation((dt*tx),0,0);
console.log(dt);
console.log(tx);
start_time=time;
gl.drawArrays (gl.TRIANGLES, 0, vertexBuffer.numItems);
window.requestAnimationFrame(animate);
}
animate(0);
</script>
</html>
<!-- end last edited snippet -->
Here is the working snippet
JSFIDDLE
Your vertex shader should look like this:
attribute vec3 a_position;' + 'uniform mat4 u_translation;' + 'void main() { gl_Position = u_translation*vec4 (a_position,1);}
In order to make objects move in space you have to multiply all your vectors and matrices with the position vector to get the result. Tranlation Wiki
You have to update your translation_prototype variable every loop cycle:
deltaTime += 0.005;
makeTranslation(tx+deltaTime,ty+deltaTime);
the deltaTime was declared outside the loop and incremented every cycle
Also your makeTranslation function should look like this:
function makeTranslation (x, y) {
translation_prototype =
[1,0,0,0,
0,1,0,0,
0,0,1,0,
x,y,0,1]
return translation_prototype;
}
(you can get rid of the return statement if you are using global variables, though is recommended to use local variables)
(I had to try this new snippet feature :D)
var webgl_canvas = document.getElementById('can');
var gl = webgl_canvas.getContext('experimental-webgl');
var triangles = [-0.5,-0.5,0,0.5,-0.5,0,0,0.5,0];
var vertexBuffer = gl.createBuffer();
var tx = 0;
var ty = 0;
var translation_prototype = [1,0,0,0,
- 0,1,0,0,
0,0,1,0,
0,0,0,1];
var vertexShader_source = 'attribute vec3 a_position;' + 'uniform mat4 u_translation;' + 'void main() { gl_Position = u_translation*vec4 (a_position,1);}';
var fragmentShader_source = 'precision mediump float;' + 'void main() { gl_FragColor = vec4 (0.9,0,0.1,1); }';
function getTimeInSeconds () {
return Date.now() * 0.001;
}
function makeTranslation (x, y) {
translation_prototype =
[1,0,0,0,
0,1,0,0,
0,0,1,0,
x,y,0,1]
return translation_prototype;
}
//Compile shaders
var buildShader = function (shaderSource, typeOfShader) {
var shader = gl.createShader(typeOfShader);
gl.shaderSource(shader, shaderSource);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert (gl.getShaderInfoLog(shader));
}
return shader;
}
var compiledVertexShader = buildShader (vertexShader_source, gl.VERTEX_SHADER);
var compiledFragmentShader = buildShader (fragmentShader_source, gl.FRAGMENT_SHADER);
//setup GLSL program
program = gl.createProgram();
gl.attachShader(program,compiledVertexShader);
gl.attachShader(program,compiledFragmentShader);
gl.linkProgram(program);
//Fill the buffer with vertex data
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(triangles), gl.STATIC_DRAW);
vertexBuffer.itemSize = 3;
vertexBuffer.numItems = 3;
gl.clear(gl.COLOR_BUFFER_BIT);
var positionLocation = gl.getAttribLocation(program,"a_position");
gl.enableVertexAttribArray(positionLocation);
gl.useProgram(program);
var shaderTranlsationMatrix = gl.getUniformLocation(program, "u_translation");
gl.uniformMatrix4fv(shaderTranlsationMatrix,false,new Float32Array(translation_prototype));
gl.vertexAttribPointer(positionLocation, vertexBuffer.itemSize, gl.FLOAT, false, 0, 0);
var startTime = 0;
var deltaTime = 0;
function animate (time) {
//Draw loop
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
deltaTime += 0.005;
makeTranslation(tx+deltaTime,ty+deltaTime);
gl.useProgram(program);
var shaderTranlsationMatrix = gl.getUniformLocation(program, "u_translation");
gl.uniformMatrix4fv(shaderTranlsationMatrix,false,new Float32Array(translation_prototype));
gl.vertexAttribPointer(positionLocation, vertexBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.drawArrays (gl.TRIANGLES, 0, vertexBuffer.numItems);
startTime = time;
window.requestAnimationFrame(animate);
}
animate(0);
<canvas id = "can" width="300" height="300">
</canvas>

Categories

Resources