We're looking for a user researcher to understand the needs of developers and designers. Is this you or someone you know? Check out the post: https://mzl.la/2IGzdXS


WebGLShader 是 WebGL API 的一部分,同时它可以是一个 (顶点)vertex 或 (片元)fragment 着色器. 一个 WebGLProgram 需要这两种类型的着色器。


要创建一个 WebGLShader 需要使用 WebGLRenderingContext.createShader,通过WebGLRenderingContext.shaderSource()然后挂接GLSL源代码 , 最后调用 WebGLRenderingContext.compileShader() 完成着色器(shader)的编译。 此时 WebGLShader 仍不是可用的形式,他需要被添加到一个 WebGLProgram里.

function createShader (gl, sourceCode, type) {
  // Compiles either a shader of type gl.VERTEX_SHADER or gl.FRAGMENT_SHADER
  var shader = gl.createShader( type );
  gl.shaderSource( shader, sourceCode );
  gl.compileShader( shader );

  if ( !gl.getShaderParameter(shader, gl.COMPILE_STATUS) ) {
    var info = gl.getShaderInfoLog( shader );
    throw "Could not compile WebGL program. \n\n" + info;
  return shader;

参看 WebGLProgram 关于添加着色器的信息.


创建一个顶点着色器( vertex shader)

注意,有很多其他方式编译和访问着色器(shader) 源代码字符串. 这些示例仅用于例证说明。

var vertexShaderSource =
  "attribute vec4 position;\n"+
  "void main() {\n"+
  "  gl_Position = position;\n"+

//从上面例子使用 createShader 函数。
var vertexShader = createShader(gl, vertexShaderSource, gl.VERTEX_SHADER)

创建一个片元着色器(fragment shader)

var fragmentShaderSource =
  "void main() {\n"+
  "  gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n"+

//从上面例子使用 createShader 函数。
var fragmentShader = createShader(gl, fragmentShaderSource, gl.FRAGMENT_SHADER)


Specification Status Comment
WebGL 1.0
Recommendation Initial definition.

Browser compatibility

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 9 4.0 (2.0) 11 12 5.1
Available in workers 未实现 44 (44) [1] 未实现 未实现 未实现
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? 25 (Yes) ? 12 8.1
Available in workers 未实现 未实现 44.0 (44) [1] 未实现 未实现 未实现

[1] This feature is behind a feature preference setting. In about:config, set gfx.offscreencanvas.enabled to true.

See also


此页面的贡献者: chuang85, carllx
最后编辑者: chuang85,