JSFiddle - React, Tailwind, and code Playground

by ShukantPal

HTML

<html>
<head>

</head>
<body>
<canvas id="webgl-canvas"></canvas>
</body>
</html>

JavaScript

const canvasElement = document.createElement("canvas");
const gl = canvasElement.getContext('webgl');

canvasElement.width = canvasElement.height = 400;
canvasElement.style = {
  width: 400,
  height: 400
};// both are acceptable

/* Add the canvas to the DOM, so that we can see it! */
document.body.appendChild(canvasElement);

const triangleVertices = [
  0, 0,
  1, 0,
  1, 1
];

const vertexShaderSource = `
  attribute vec2 aVertexPosition;

  void main(void) {
    gl_Position = vec4(aVertexPosition, 1.0, 1.0);
  }
`;

const fragmentShaderSource = `
  void main(void) {
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
  }
`;

/* generateShader & generateProgram are at the bottom */
const vertexShader = generateShader(gl, vertexShaderSource,
                                    gl.VERTEX_SHADER);
const fragmentShader = generateShader(gl, fragmentShaderSource, 
                                      gl.FRAGMENT_SHADER);

const program = generateProgram(gl, vertexShader, fragmentShader);
const aVertexPositionLocation = gl.getAttribLocation(
  program, "aVertexPosition");

const vertexBuffer = gl.createBuffer();

gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, Float32Array.from(triangleVertices),
              gl.STATIC_DRAW);

gl.useProgram(program);
gl.enableVertexAttribArray(aVertexPositionLocation);
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.vertexAttribPointer(aVertexPositionLocation, 2, gl.FLOAT,
                       false, 0, 0);
gl.drawArrays(gl.TRIANGLES, 0, 3);

function generateShader(gl, source, type) {
  const glShader = gl.createShader(type);
  gl.shaderSource(glShader, source);
  gl.compileShader(glShader);
  
  if (gl.getShaderParameter(glShader, gl.COMPILE_STATUS))
     return glShader;
  
  throw new Error(`${source} shader couldn't compile!`);
}

function generateProgram(gl, _vertexShader, _fragmentShader) {
  const glProgram = gl.createProgram();
  gl.attachShader(glProgram, _vertexShader);
 ...