Published
Edited
Sep 8, 2021
Insert cell
# Assignment 3 Scaffold Breakdown
Insert cell
gl = {
const canvas = html`<canvas width="378", height="256"></canvas>` // Intialize the canvas
const gl = canvas.getContext("webgl2"); // Get the context of the app, webgl2
gl.clearColor(0.25, 0.25, 0.25, 1); // Set the background color
gl.clear(gl.COLOR_BUFFER_BIT); // Background stuff
gl.enable(gl.DEPTH_TEST); // Background stuff
return gl; // Return gl so we can initialize gl
}
Insert cell
shaders = {
const vs = `#version 300 es // Declare the version we are working in

in vec2 position; // Attribute for postions
in vec3 normal; // Attribute for the normals

uniform float aspect; // Window aspect ratio: window.width/window.height
out vec3 fragNormal; // Variable whose value will be associated with the gl_position.

void main () {
gl_Position = vec4(position.x/aspect, position.y, 0, 1); // gl_Position must be set with a vec4 value.
fragNormal = normalize(normal); // Normalize the normals
}`;

const fs = `#version 300 es // Again we must declare the version we are working with
precision mediump float; // Set the precision inside the fragment shader

in vec3 fragNormal; // Input for the normals

out vec4 outColor; // User-defined output variable for

void main () {
vec3 N = normalize(fragNormal); // Normalize the normals
vec3 color = (N+1.0)/2.0;
outColor = vec4(abs(N), 1);
}`;

return [vs, fs];
}
Insert cell
// Define the vectorAttributes for the positions and the normals
vertexAttributes = [
{
position: {
numComponents: 2,
data: [1, 0, 0, 1, -1, -1]
}, // Attribute position
normal: {
numComponents: 3,
data: [1, 0, 1, 0, 1, 1, -1, -1, -1]
} // Attribtue normal
}
]
Insert cell
programInfo = {
return twgl.createProgramInfo(gl, shaders); // Compile shaders and create the program
}
Insert cell
// Create the buffer info from the arrays
bufferInfoArray = vertexAttributes.map(
(d) =>
twgl.createBufferInfoFromArrays(gl, d)
)

Insert cell
viewof useAspectRatio = Inputs.toggle({ label: "Use Window Aspect Ratio" })
Insert cell
{
yield gl.canvas;
const uniforms = {
aspect: useAspectRatio ? gl.canvas.width / gl.canvas.height : 1
};
const request = requestAnimationFrame(function render(time) {
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.useProgram(programInfo.program);
bufferInfoArray.forEach((bufferInfo) => {
twgl.setUniforms(programInfo, uniforms);
twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo);
twgl.drawBufferInfo(gl, bufferInfo);
});
requestAnimationFrame(render);
});
invalidation.then(() => cancelAnimationFrame(request));
}
Insert cell
twgl = require("twgl.js")
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