<canvas width="512" height="512"></canvas>
canvas{
  width:512px;
  height:512px;
}
const canvas = document.querySelector('canvas');
const gl = canvas.getContext('webgl');

const vertexShader =
`
attribute vec4 position;
void main() {
  gl_Position = position;
}
`

const fragmentShader =
`
precision mediump float;
uniform float size;

void main() {
  if(
   mod(gl_FragCoord.x,size)<1.0 ||
   mod(gl_FragCoord.y,size)<1.0
  ){
    gl_FragColor = vec4(0.0, 0.0, 0.0, 0.8);
  }else {discard;}                      
}
`

// Compile vertex shader
const vs = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vs, vertexShader);
gl.compileShader(vs);

// Compile fragment shader
const fs = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fs, fragmentShader);
gl.compileShader(fs);

// Create and launch the WebGL program
const program = gl.createProgram();
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);

// Clear the canvas
gl.clear(gl.COLOR_BUFFER_BIT);
// Activate grid shaders
gl.useProgram(program);

// Set size value
const size = gl.getUniformLocation(program, 'size');
gl.uniform1f(size, 32); // Cell Size

// Four vertices represent corners of the canvas
// Each row is x,y,z coordinate
// -1,-1 is left bottom, z is always zero, since we draw in 2d
const vertices = new Float32Array([
 1.0, 1.0, 0.0, 
-1.0, 1.0, 0.0, 
 1.0, -1.0, 0.0, 
-1.0, -1.0, 0.0
]);

// Attach vertices to a buffer
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

// Set position to point to buffer
const position = gl.getAttribLocation(program, 'position');

gl.vertexAttribPointer(
	position, // target
	3, // x,y,z
	gl.FLOAT, // type
	false, // normalize
	0, // buffer offset
	0 // buffer offset
);

gl.enableVertexAttribArray(position);

// Finally draw our 4 vertices
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.