百叶窗效果没出来,大家帮我看看哪有问题。

来源:3-11 实战:实现动态入场效果

慕运维5378130

2024-02-28

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .text {
        height: 560px;
        width: 560px;
        border: 1px solid #000;
        margin-top: 5vh;
        margin-left: calc(50vw - 280px);
        background-color: #0003;
      }
      body {
        height: 100vh;
        overflow: hidden;
        margin: 0;
      }
    </style>
  </head>
  <body>
    <script src="../lib.js"></script>
    <script>
      // 使用attribute变量
      const canvas = document.createElement("canvas");
      document.body.appendChild(canvas);
      canvas.classList.add("text");
      const gl = canvas.getContext("webgl");

      // 第一步编写着色器源(着色器执行内容)
      const VERTEX_SHADER_SOURCE = `
        attribute vec4 aPosition;
        varying vec4 vPosition;

        void main() {
          vPosition = aPosition;
          gl_Position = aPosition;
        }
      `;
      const FRAGMENT_SHADER_SOURCE = `
        precision lowp float;
        uniform float uHeight;
        varying vec4 vPosition;
        uniform float list[5]; // 声明一个数组变量

        void main() {
          for(int i = 0; i < 5; i++) {
            if (vPosition.y > list[i + 1] && vPosition.y < list[i]) {
              if (vPosition.y > uHeight - float(i) * 0.5) {
                gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
              }
            }
          }
        }
      `;
      const program = initShader(
        gl,
        VERTEX_SHADER_SOURCE,
        FRAGMENT_SHADER_SOURCE
      );

      // 获取attribute变量
      const aPosition = gl.getAttribLocation(program, "aPosition"); // 返回变量aPosition的存储地址
      const uHeight = gl.getUniformLocation(program, "uHeight")
      const uList = gl.getUniformLocation(program, "list")
      gl.uniform1f(uList, [1.0, 0.5, 0.0, -0.5, -1.0])
      const points = new Float32Array([
        -1.0, -1.0,
         1.0, -1.0, 
         -1.0, 1.0,
          1.0, 1.0,
      ]);
      const buffer = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
      gl.bufferData(gl.ARRAY_BUFFER, points, gl.STATIC_DRAW);
      gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0);
      gl.enableVertexAttribArray(aPosition);

      let value = 1;
      function run() {
        value -= 0.01;

        gl.uniform1f(uHeight, value);
        gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);

        requestAnimationFrame(run)
      }
      run();
    </script>
  </body>
</html>

写回答

1回答

yancy

2024-03-02

给uList赋值的时候,应该使用 gl.uniform1fv 后边的v不能省略。因为 uList 本身为一个 float 的列表,所以不能通过 1f 这种方式来赋值。

1
0

WebGL+Three.js 入门与实战,系统学习 Web3D 技术

前端的技术蓝海,涨薪好选择

1081 学习 · 294 问题

查看课程