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

{
// 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);
}
{
// 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 = 3;
// gl.drawArrays(gl.TRIANGLE_STRIP, offset, vertexCount);
gl.drawArrays(gl.TRIANGLES, offset, vertexCount)
}
Insert cell
Insert cell
Insert cell
positionBuffer = createBuffer(gl, data.positions)
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 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
function createProgram(gl, vertShaderStr, fragShaderStr) {
const vertShader = compileShader(gl, vertShaderStr, gl.VERTEX_SHADER)
const fragShader = compileShader(gl, fragShaderStr, gl.FRAGMENT_SHADER)

const program = gl.createProgram()

gl.attachShader(program, vertShader)
gl.attachShader(program, fragShader)

gl.linkProgram(program)
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
throw new Error(`Could not link shaders: ${gl.getProgramInfoLog(program)}`)
}

return program
}
Insert cell
function compileShader(gl, shaderStr, shaderType) {
const shader = gl.createShader(shaderType)
gl.shaderSource(shader, shaderStr)
gl.compileShader(shader)
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
throw new Error('Shader compile failed: ' + gl.getShaderInfoLog(shader))
}

return shader
}
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