JSFiddle - React, Tailwind, and code Playground

by soulwire

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebGL Drawing Effect</title>
    <style>
        canvas { display: block; margin: 0 auto; }
    </style>
</head>
<body>
<canvas id="glCanvas"></canvas>
</body>
</html>

JavaScript

function main() {
  const canvas = document.getElementById("glCanvas")
  canvas.width = 800
  canvas.height = 600
  const gl = canvas.getContext("webgl")

  if (!gl) {
    alert("WebGL not supported")
    throw new Error("WebGL not supported")
  }

  // Vertex Shader
  const vsSource = `
        attribute vec2 aPosition;
        attribute vec2 aTexCoord;
        varying vec2 vTexCoord;
        void main() {
            gl_Position = vec4(aPosition, 0.0, 1.0);
            vTexCoord = aTexCoord;
        }
    `

  // Fragment Shader
  const fsSource = `
        precision mediump float;
        uniform sampler2D uTexture;
        uniform float uProgress; // 0.0 to 1.0
        uniform float uTotalSegments; // Total number of segments
        varying vec2 vTexCoord;

        void main() {
            vec4 texColor = texture2D(uTexture, vTexCoord);

            // Decode RGB into a single color index
            float colorIndex = texColor.r * 255.0 * 256.0 * 256.0 +
                               texColor.g * 255.0 * 256.0 +
                               texColor.b * 255.0;

            // Normalize the index and compare with progress
            float normalizedIndex = colorIndex / uTotalSegments;
            if (normalizedIndex <= uProgress) {
                gl_FragColor = texColor;
            } else {
                discard;
            }
        }
    `

  // Compile Shader
  function compileShader(gl, source, type) {
    const shader = gl.createShader(type)
    gl.shaderSource(shader, source)
    gl.compileShader(shader)
    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
      console.error("Error compiling shader:", gl.getShaderInfoLog(shader))
      gl.deleteShader(shader)
      return null
    }
    return shader
  }

  const vertexShader = compileShader(gl, vsSource, gl.VERTEX_SHADER)
  const fragmentShader = compileShader(gl, fsSource, gl.FRAGMENT_SHADER)

  // Link Program
  const program = gl.createProgram()
  gl.attachShader(program,...