Published
Edited
Dec 16, 2020
2 forks
Insert cell
md`# WebGL Triangle #3: Indexed(EBO)`
Insert cell
canvas = DOM.canvas(width, height);
Insert cell
{
draw()
}
Insert cell
vao = {
const vao = gl.createVertexArray()
gl.bindVertexArray(vao)
{
// connect buffers and attributes
const numComponents = 2;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.vertexAttribPointer(
attributeLocations.position,
numComponents,
type,
normalize,
stride,
offset);
gl.enableVertexAttribArray(attributeLocations.position);
}
{
// EBO
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ebo)
}
return vao
}
Insert cell
function draw() {
// clear
gl.clearColor(1., 1., 1., 1.);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

// bind VAO
gl.bindVertexArray(vao)
{
// connect uniforms
gl.uniform2f(uniformLocations.resolution, width, height);
gl.uniform4fv(uniformLocations.color, new Float32Array(data.color));
gl.uniformMatrix4fv(uniformLocations.transform, false, new Float32Array(transform));
}
// use program
gl.useProgram(program);

// draw
const offset = 0;
const vertexCount = 6;
const indexType = gl.UNSIGNED_SHORT;
gl.drawElements(gl.TRIANGLES, vertexCount, indexType, offset)
}
Insert cell
Insert cell
indices = [
0, 1, 2,
0, 3, 1
]
Insert cell
Insert cell
positionBuffer = createBuffer(gl, data.positions)
Insert cell
ebo = createIndexBuffer(gl, indices)
Insert cell
attributeLocations = {
return {
position: gl.getAttribLocation(program, "in_position"),
}
}
Insert cell
uniformLocations = {
return {
resolution: gl.getUniformLocation(program, "u_resolution"),
transform: gl.getUniformLocation(program, "u_transform"),
color: gl.getUniformLocation(program, "u_color")
}
}
Insert cell
program = createProgram(gl, vertexShaderSource, fragmentShaderSource)
Insert cell
gl = canvas.getContext('webgl2')
Insert cell
height = width * 0.75
Insert cell
Insert cell
Insert cell
function createIndexBuffer(gl, indices) {
const buffer = gl.createBuffer()
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer)
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW)
return buffer
}
Insert cell
function createBuffer(gl, data) {
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW);
return buffer;
}
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