5

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.

2
  • Is that all your code? Have you setup the GL context correctly? Can you create a jsFiddle so we can see all of your code? Commented Nov 30, 2012 at 17:44
  • I have never used jsFiddle but here is a link with my code on jsFiddle jsfiddle.net/J8Wkg/1 Commented Nov 30, 2012 at 21:17

1 Answer 1

3

The problem is the following line:

gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

new Float32Array(vertices) is returning [NaN, NaN, NaN]. This is because the Float32Array contructor expects an array of Numbers and not an array of Vectors.

You'll need to pass new Float32Array() a single one dimensional array of Numbers

If you want to fix it you'll have to write a function to convert your array of Vectors into a Float32Array. Something like this:

function vectorsToFloatArray(vertices) {
    var numbers = [];

    for(var i = 0; i < vertices.length; i++) {
        numbers.push(vertices[i].x);
        numbers.push(vertices[i].y);
        numbers.push(vertices[i].z);
    }

    return new Float32Array(numbers);
}

And remember to update the gl.bufferData() and item size:

    gl.bufferData(gl.ARRAY_BUFFER, vectorsToFloatArray(vertices), gl.STATIC_DRAW);
    triangleVertexPositionBuffer.itemSize = 3;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help I now have it working do you know how to make an array that will take two vectors E[0] = [V[0], V[1]]; and then use that to draw to the screen

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.