Published
Edited
Oct 19, 2021
5 stars
Insert cell
Insert cell
Insert cell
gl = {
const canvas = DOM.canvas(578, 256);
// or html`<canvas width="578", height="256"></canvas>`
const gl = canvas.getContext("webgl2");
gl.clearColor(0.25, 0.25, 0.25, 1);
gl.enable(gl.DEPTH_TEST);
return gl;
}
Insert cell
Insert cell
shaders = {
const vs = `#version 300 es

in vec3 position; // Attribute
in vec3 normal; // Attribute
uniform float asp; // Windo aspect ratio: hindow.width/window.height
out vec3 fragNormal; // Variable whose value will be associated with the gl_position.

void main () {
gl_Position = vec4(position.x/asp, position.yz, 1);
// Note: gl_Position is a A predefined vec4 variable. It must be set with a vec4 value.
fragNormal = normalize(normal);
}`;

const fs = `#version 300 es
precision mediump float;

in vec3 fragNormal;

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

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

return [vs, fs];
}
Insert cell
Insert cell
Insert cell
programInfo = {
errorBlock.style.height = "20px";
errorBlock.innerHTML = "Program Shader compilation successful";
return twgl.createProgramInfo(gl, shaders, (message) => { // Combile the shaders and create a shader program.
errorBlock.style.height = "400px";
errorBlock.innerHTML = "Program Shader compilation error\n" + message;
});
}
Insert cell
Insert cell
Insert cell
Insert cell
vertexAttributes = [
{
position: {
numComponents: 3,
data: [1, 0, 0, 0, 1, 0, -1, -1, 0]
}, // Attribute position
normal: {
numComponents: 3,
data: [1, 0, 1, 0, 1, 1, -1, -1, -1]
} // Attribtue normal
}
]
Insert cell
md`### Step 3c: **twgl code here**.
- Create vertex attribute buffers.
Use *twgl.createBufferInfoFromArrays* to create buffers under gl context.`
Insert cell
bufferInfoArray = vertexAttributes.map((d) =>
twgl.createBufferInfoFromArrays(gl, d)
)
Insert cell
Insert cell
Insert cell
{
const uniforms = {
asp: 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));
return gl.canvas;
}
Insert cell
md`### External Libraries`
Insert cell
m4 = twgl.m4
Insert cell
twgl = require("twgl.js")
Insert cell
require.resolve("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