WebGL API 的 WebGLShader 可以是一个顶点着色器(vertex shader)或片元着色器(fragment shader)。每个 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"+
  "}\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"+
  "}\n";

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

规范

Specification Status Comment
WebGL 1.0
WebGLShader
Recommendation 初次定义

浏览器兼容性

 
Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
Basic supportChrome Full support 9Edge Full support 12Firefox Full support 4IE Full support 11Opera Full support 12Safari Full support 5.1WebView Android Full support YesChrome Android Full support 25Edge Mobile Full support YesFirefox Android Full support YesOpera Android Full support 12Safari iOS Full support 8.1Samsung Internet Android Full support Yes
Available in workers
Experimental
Chrome No support NoEdge No support NoFirefox Full support 44
Disabled
Full support 44
Disabled
Disabled From version 44: this feature is behind the gfx.offscreencanvas.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.
IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoEdge Mobile No support NoFirefox Android No support NoOpera Android No support NoSafari iOS No support NoSamsung Internet Android No support No

Legend

Full support  
Full support
No support  
No support
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.
User must explicitly enable this feature.
User must explicitly enable this feature.

参阅

文档标签和贡献者

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