Published
Edited
Sep 23, 2021
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
draw = (vertexBuffer, indexBuffer) => {
gl.viewport(0, 0, width, height);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
let offset = 0, stride = 2 * 3 * 4 // 4 is the size of a float in bytes
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, vertexBuffer.numFloats, gl.FLOAT, false, stride, offset);
offset = 3 * 4 // 4 is the size of a float in bytes
gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, vertexBuffer.numFloats, gl.FLOAT, false, stride, offset);
offset = 0;
// To draw in this new way, we bind the index buffer and use gl.drawElements to draw gl.TRIANGLES based on the vertex and index information in the two buffers
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer)
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
}
Insert cell
{
// Init buffers
let squareVertexBuffer;
let vertices = [];
squareVertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexBuffer);

// below is how you interleave positions and colors into a single array and then VBO
vertices.push(-.5); vertices.push(-.5); vertices.push(0.0); // v1 positions
vertices.push(1.0); vertices.push(0.0); vertices.push(0.0); // v1 colors

vertices.push(.5); vertices.push(-.5); vertices.push(0.0); // v2 positions
vertices.push(0.0); vertices.push(1.0); vertices.push(0.0); // v2 colors

vertices.push(.5); vertices.push(.5); vertices.push(0.0); // v3 positions
vertices.push(0.0); vertices.push(0.0); vertices.push(1.0); // v3 colors

vertices.push(-.5); vertices.push(.5); vertices.push(0.0); // v4 positions
vertices.push(0.0); vertices.push(0.0); vertices.push(0.0); // v4 colors


gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); // use 4 bytes float
squareVertexBuffer.numFloats = 3; // three floats per vertex
squareVertexBuffer.numVertices = 4; // number of vertices in the buffer

var indices = [0,1,2, 0,2,3];
let squareVertexIndexBuffer;
squareVertexIndexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, squareVertexIndexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
squareVertexIndexBuffer.itemsize = 1;
squareVertexIndexBuffer.numItems = 6;
draw(squareVertexBuffer, squareVertexIndexBuffer)
return "OK"
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more