I am trying to make A cube of triangles using JavaScript and Webgl. The cube will use face edge vertex structure using arrays , but when I use arrays there is nothing drawn to screen.
This how I declare the array.
function Vector(x,y,z){
this.x = x;
this.y = y;
this.z = z;
}
var V = new Array;
V[0] = new Vector(0.0, 1.0, 0.0);
V[1] = new Vector(-1.0, -1.0, 0.0);
V[2] = new Vector(1.0, -1.0, 0.0);
function initBuffers() {
triangleVertexPositionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
var vertices = [
V[0],
V[1],
V[2]
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
triangleVertexPositionBuffer.itemSize = 1;
triangleVertexPositionBuffer.numItems = 3;
I am not sure why it doesn’t draw to screen if anyone can help it would be appreciated.
The problem is the following line:
new Float32Array(vertices)is returning[NaN, NaN, NaN]. This is because theFloat32Arraycontructor expects an array ofNumbers and not an array ofVectors.You’ll need to pass
new Float32Array()a single one dimensional array ofNumbersIf you want to fix it you’ll have to write a function to convert your array of
Vectors into aFloat32Array. Something like this:And remember to update the
gl.bufferData()and item size: