WebGLShader

WebGLShader 属于 WebGL API and can either be a vertex or a fragment shader. A WebGLProgram requires both types of shaders.

描述

To create a WebGLShader use WebGLRenderingContext.createShader , then hook up the GLSL source code using WebGLRenderingContext.shaderSource() , and finally invoke WebGLRenderingContext.compileShader() to finish and compile the shader. At this point the WebGLShader is still not in a usable form and must still be attached to a 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 for information on attaching the shaders.

范例

Creating a vertex shader

Note that there are many other strategies for writing and accessing shader source code strings. These example are for illustration purposes only.

var vertexShaderSource =
  'attribute vec4 position;\n' +
  'void main() {\n' +
  '  gl_Position = position;\n' +
  '}\n';
//Use the createShader function from the example above
var vertexShader = createShader(gl, vertexShaderSource, gl.VERTEX_SHADER)
					

Creating a fragment shader

var fragmentShaderSource =
  'void main() {\n' +
  '  gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n' +
  '}\n';
//Use the createShader function from the example above
var fragmentShader = createShader(gl, fragmentShaderSource, gl.FRAGMENT_SHADER)
					

规范

规范 状态 Comment
WebGL 1.0
The definition of 'WebGLShader' in that specification.
Recommendation 初始定义。

浏览器兼容性

更新 GitHub 上的兼容性数据
Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
WebGLShader Chrome 9 Edge 12 Firefox 4 IE 11 Opera 12 Safari 5.1 WebView Android Yes Chrome Android 25 Firefox Android Yes Opera Android 12 Safari iOS 8 Samsung Internet Android 1.5
Available in workers
Chrome No Edge No Firefox 44
Disabled
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 Opera No Safari No WebView Android No Chrome Android No Firefox Android No Opera Android No Safari iOS No Samsung Internet Android No

图例

完整支持
完整支持
不支持
不支持
实验。期望将来行为有所改变。
实验。期望将来行为有所改变。
用户必须明确启用此特征。
用户必须明确启用此特征。

另请参阅