JSFiddle - React, Tailwind, and code Playground
by jcubed111
HTML
<canvas id="main"></canvas>
CSS
body{
margin: 0;
overflow: hidden;
}
JavaScript
let canvas = document.getElementById('main');
canvas.width = innerWidth;
canvas.height = innerHeight;
let gl = canvas.getContext('webgl');
gl.clearColor(0, 0, 0, 1);
gl.clearDepth(1.0);
gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
function loadShader(type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
return shader;
}
const vertexShader = loadShader(gl.VERTEX_SHADER, `
attribute vec4 vertIn;
attribute vec4 colorIn;
uniform vec2 scale;
varying mediump vec4 vColor;
void main() {
gl_Position = vec4(scale * vertIn.xy, vertIn.zw);
vColor = colorIn;
}
`);
const fragmentShader = loadShader(gl.FRAGMENT_SHADER, `
varying mediump vec4 vColor;
void main() {
gl_FragColor = vColor;
}
`);
// Create the shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
gl.useProgram(shaderProgram);
const vertInPosition = gl.getAttribLocation(shaderProgram, 'vertIn');
const colorInPosition = gl.getAttribLocation(shaderProgram, 'colorIn');
const scalePosition = gl.getUniformLocation(shaderProgram, 'scale');
class Block{
constructor() {
this.buffer = gl.createBuffer();
this.bufferDirty = true;
this.verts = [];
this.addVert(0, 0, 0, 0, 1, 1);
this.addVert(1, 1, 0, 1, 0, 1);
this.addVert(-1, 1, 0, 1, 1, 0);
}
addVert(x, y, z, r, g, b, a=1) {
this.verts.push(x, y, z, r, g, b, a);
this.bufferDirty = true;
}
addBufferData(){
gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this.verts), gl.STATIC_DRAW);
this.bufferDirty = false;
}
render() {
if(this.bufferDirty) this.addBufferData();
...