Public
Edited
Sep 7, 2022
Insert cell
# Webgl Triangle
Insert cell
## External Libraries
Insert cell
twgl = require("twgl.js")
Insert cell
require.resolve("twgl.js")
Insert cell
m4 = twgl.m4
Insert cell
Insert cell
gl = {
const canvas = DOM.canvas(600, 400);
// 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;
in vec3 normal;

uniform float aspectR; // window aspect ratio: width/height
out vec3 fragNormal;

void main(){
gl_Position = vec4(position.x/aspectR, position.yz, 1);
fragNormal = normalize(normal);
}
`;

const fs = `#version 300 es
precision mediump float;
in vec3 fragNormal;
out vec4 outColor;
void main(){
vec3 N = normalize(fragNormal);
outColor = vec4(abs(N), 1);
}
`;
return [vs, fs]
}
Insert cell
Insert cell
errorBlock = html`<textarea style="height : 20px; width : ${width}px; font-size: 0.8em; display: block"></textarea>`
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
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]
} // Attribute normal
}
]
Insert cell
Insert cell
bufferInfoArray = vertexAttributes.map((d)=>twgl.createBufferInfoFromArrays(gl, d));
Insert cell
Insert cell
viewof useAspectRatio = Inputs.toggle({ label: "Use Window Aspect Ratio" })
Insert cell
{
const uniforms = {
aspectR: useAspectRatio? gl.canvas.width / gl.canvas.height : 1
};

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);
}
);
return gl.canvas
}
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