WebGL 着色器程序无效

WebGL shader program not valid

学习我的第一个 WebGL,尝试在 canvas WebGL 上下文中绘制图像(来自 url)。

我的目标是在 canvas 上有一个背景图像,顶部有一个透明图像,显示背景,最终使用 captureStream。

虽然我的着色器正在成功编译(根据 gl.COMPILE_STATUS),但似乎我缺少一个有效程序的步骤:

  const vs = gl.createShader(gl.VERTEX_SHADER)
  gl.shaderSource(vs, document.getElementById('draw-image-vertex-shader').innerText)
  gl.compileShader(vs)

  const fs = gl.createShader(gl.FRAGMENT_SHADER)
  gl.shaderSource(fs, document.getElementById('draw-image-fragment-shader').innerText)
  gl.compileShader(fs)

  var vs_success = gl.getShaderParameter(vs, gl.COMPILE_STATUS);
  console.log( vs_success )

  var fs_success = gl.getShaderParameter(fs, gl.COMPILE_STATUS);
  console.log( fs_success )

  const program = gl.createProgram()

  gl.useProgram(program)

我得到:

WebGL: INVALID_OPERATION: useProgram: program not valid

这是着色器:

<script id="draw-image-vertex-shader" type="glsl">
  attribute vec4 a_position;
  attribute vec2 a_texcoord;
  uniform mat4 u_matrix;
  varying vec2 v_texcoord;
  void main() {
     gl_Position = u_matrix * a_position;
     v_texcoord = a_texcoord;
  }
</script>
<script id="draw-image-fragment-shader" type="glsl">
  precision mediump float;
  varying vec2 v_texcoord;
  uniform sampler2D u_texture;
  void main() {
     gl_FragColor = texture2D(u_texture, v_texcoord);
  }
</script>

任何见解都将是惊人的,非常感谢:)

您必须将 shders 附加到程序对象并且您必须 link 程序对象:

const vs = gl.createShader(gl.VERTEX_SHADER)
gl.shaderSource(vs, document.getElementById('draw-image-vertex-shader').innerText)
gl.compileShader(vs)
if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) 
    console.log(gl.getShaderInfoLog(vs));

const fs = gl.createShader(gl.FRAGMENT_SHADER)
gl.shaderSource(fs, document.getElementById('draw-image-fragment-shader').innerText)
gl.compileShader(fs)
if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) 
    console.log(gl.getShaderInfoLog(fs));

const program = gl.createProgram()
gl.attachShader(program, vs)
gl.attachShader(program, fs)

gl.linkProgram(program)
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) 
    console.log(gl.getProgramInfoLog(program))

gl.useProgram(program)