canvas使用webgl实现太空彩虹效果代码

代码语言:html

所属分类:其他

代码描述:canvas使用webgl实现太空彩虹效果代码

代码标签: canvas 使用 webgl 太空 彩虹

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  

  
  
<style>
body {
  margin: 0;
}
</style>

  
  
  
</head>

<body translate="no">
  <canvas id="canvas"></canvas>
  
      <script  >
(function () {
  const canvas = document.getElementById('canvas');
  const gl = canvas.getContext('webgl2');

  if (!gl) {
    console.error("WebGL not supported");
    return;
  }

  function resizeCanvasToDisplaySize(canvas) {
    const displayWidth = window.innerWidth;
    const displayHeight = window.innerHeight;

    if (canvas.width !== displayWidth || canvas.height !== displayHeight) {
      canvas.width = displayWidth;
      canvas.height = displayHeight;
    }
  }

  const vertexShaderSource = `
    attribute vec2 aPosition;
    void main() {
      gl_Position = vec4(aPosition, 0.0, 1.0);
    }
  `;

  const fragmentShaderSource = `
    precision highp float;

    uniform float iTime;
    uniform vec2 iResolution;

    void main() {
      vec2 uv = (gl_FragCoord.xy * 5.5 - iResolution.xy) / iResolution.y;
      vec2 uv0 = uv;
      vec3 finalColor = vec3(0.0);

      for (float i = 0.0; i < 1.0; i++) {
        uv = uv * 7.0 - 0.9;
        float d = length(uv) * exp(-length(uv0));
        vec3 col = vec3(0.5, 0.5, 0.5) +
                   vec3(0.5, 0.5, 0.5) * cos(1.2 * (vec3(1.0) * (length(uv0) + i * 0.4 + iTime * 0.2) + vec3(0.263, 0.416, 0.557)));

        d = sin(d * 6.0 + iTime * 0.1) / 10.0;
        d = abs(d);

        d = pow(0.00000001 / d, 0.04);

        finalColor += col * d;
      }

      gl_FragColor = vec4(finalColor, 1.0);
    }
  `;

  function createShader(gl, type, source) {
    const shader = gl.createShader(type);
    gl.shaderSource(shader, source);
    gl.compileShader(shader);
    const success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
    if (success) {
      return shader;
    }

    console.error('Shader compile failed with: ' + gl.getShaderInfoLog(shader));
    gl.deleteShader(shader);
  }

  function createProgram(gl, vertexShader, fragmentShader) {
    const program = gl.createP.........完整代码请登录后点击上方下载按钮下载查看

网友评论0