Published
Edited
Jun 3, 2021
Insert cell
md`# WebGL Instancing Template`
Insert cell
canvas = DOM.canvas(width, height);
Insert cell
{
draw()
}
Insert cell
Insert cell
function draw() {
// clear
gl.clearColor(1., 1., 1., 1.);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

// use program
gl.useProgram(program);

// bind VAO
gl.bindVertexArray(vao)

{
// connect uniforms
gl.uniform2f(uniformLocations.resolution, width, height);
}
// draw
const offset = 0;
const vertexCount = 6;
const indexType = gl.UNSIGNED_SHORT;
const instanceCount = data.pos.length;
gl.drawElementsInstanced(gl.TRIANGLES, vertexCount, indexType, offset, instanceCount)
}
Insert cell
Insert cell
Insert cell
posBuffer = createBuffer(gl, data.pos.flat())
Insert cell
sizeBuffer = createBuffer(gl, data.size)
Insert cell
shapePosBuffer = createBuffer(gl, shapeData.positions)
Insert cell
Insert cell
attributeLocations = {
return {
position: gl.getAttribLocation(program, "in_position"),
centerPos: gl.getAttribLocation(program, "in_centerPos"),
size: gl.getAttribLocation(program, "in_size"),
}
}
Insert cell
uniformLocations = {
return {
resolution: gl.getUniformLocation(program, "u_resolution"),
}
}
Insert cell
program = createProgram(gl, vertexShaderSource, fragmentShaderSource)
Insert cell
gl = canvas.getContext('webgl2')
Insert cell
height = width * 0.75
Insert cell
width
Insert cell
Insert cell
fragmentShaderSource = `#version 300 es

precision highp float;

out vec4 fragColor;

void main() {
fragColor = vec4(0., 0., 0., 1.);
}
`
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