xxxxxxxxxx
74
let myShader;
const cols = 10;
const rows = 10;
const cellSize = 9;
const vertSrc = `#version 300 es
precision mediump float;
uniform mat4 uProjectionMatrix;
uniform mat4 uModelViewMatrix;
in vec3 aPosition;
in vec3 aNormal;
in vec3 aVertexColor;
in float aDistance;
out vec3 vVertexColor;
void main(){
vec4 positionVec4 = vec4(aPosition, 1.0);
positionVec4.xyz += aDistance * aNormal * 3.0;
vVertexColor = aVertexColor;
gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;
}
`;
const fragSrc = `#version 300 es
precision mediump float;
in vec3 vVertexColor;
out vec4 outColor;
void main(){
outColor = vec4(vVertexColor, 1.0);
}
`;
function setup(){
createCanvas(100, 100, WEBGL);
// Create and apply the custom shader.
myShader = createShader(vertSrc, fragSrc);
shader(myShader);
noStroke();
describe('A blue grid, which moves away from the mouse position, on a gray background.');
}
function draw(){
background(200);
// Draw the grid in the middle of the screen.
translate(-cols*cellSize/2, -rows*cellSize/2);
beginShape(QUADS);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
// Calculate the cell position.
let x = i * cellSize;
let y = j * cellSize;
fill(i/rows*255, j/cols*255, 255);
// Calculate the distance from the corner of each cell to the mouse.
let distance = dist(x,y, mouseX, mouseY);
// Send the distance to the shader.
setAttribute('aDistance', min(distance, 100));
vertex(x, y);
vertex(x + cellSize, y);
vertex(x + cellSize, y + cellSize);
vertex(x, y + cellSize);
}
}
endShape();
}