const numVerts = 51; // number of vertices
createCanvas(400, 400, WEBGL);
// Vertex shader: we pass along the stroke weight attribute
attribute vec3 aPosition;
attribute float aStrokeWeight;
uniform mat4 projectionMatrix;
uniform mat4 modelViewMatrix;
varying float vStrokeWeight;
vStrokeWeight = aStrokeWeight;
gl_Position = projectionMatrix * modelViewMatrix * vec4(aPosition, 1.0);
// Fragment shader: use the stroke weight to modulate the color
varying float vStrokeWeight;
// Here we simply use the stroke weight to set a grayscale value.
gl_FragColor = vec4(vStrokeWeight, vStrokeWeight, vStrokeWeight, 1.0);
myShader = new p5.Shader(this._renderer, vertShader, fragShader);
// Create buffers for vertex positions and stroke weights
positions = new Float32Array(numVerts * 3);
strokeWeights = new Float32Array(numVerts);
for (let i = 0; i < numVerts; i++) {
// Create a spiral-like line
let r = map(i, 0, numVerts - 1, 0, width / 3);
positions[i * 3 + 1] = y;
positions[i * 3 + 2] = z;
// Stroke weight ranging from 1 (at the first vertex) to 0 (at the last)
strokeWeights[i] = map(i, 0, numVerts - 1, 1.0, 0.0);
let gl = this._renderer.GL;
// Create and bind the position buffer
positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);
// Create and bind the stroke weight buffer
weightBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, weightBuffer);
gl.bufferData(gl.ARRAY_BUFFER, strokeWeights, gl.STATIC_DRAW);
// Activate our custom shader
let gl = this._renderer.GL;
gl.useProgram(myShader.program);
// --- Set up the vertex position attribute ---
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const posLoc = gl.getAttribLocation(myShader.program, 'aPosition');
gl.enableVertexAttribArray(posLoc);
// 3 components per vertex (x, y, z)
gl.vertexAttribPointer(posLoc, 3, gl.FLOAT, false, 0, 0);
// --- Set up the stroke weight attribute ---
gl.bindBuffer(gl.ARRAY_BUFFER, weightBuffer);
const weightLoc = gl.getAttribLocation(myShader.program, 'aStrokeWeight');
gl.enableVertexAttribArray(weightLoc);
// 1 component per vertex (the stroke weight)
gl.vertexAttribPointer(weightLoc, 1, gl.FLOAT, false, 0, 0);
// Draw the vertices as a line strip
gl.drawArrays(gl.LINE_STRIP, 0, numVerts);
gl.disableVertexAttribArray(posLoc);
gl.disableVertexAttribArray(weightLoc);