WebGLProgram 是 WebGL API 的一部分,它由两个WebGLShaders (webgl 着色器)组成,分别为顶点着色器和片元着色器(两种着色器都是采用 GLSL 语言编写的)。创建一个 WebGLProgram 需要调用 GL 上下文的createProgram() 方法,然后调用attachShader()方法附加上着色器,之后你才能将它们连接到一个可用的程序。

WebGLProgram 的创建过程请参考下面的代码:

var program = gl.createProgram();

// 添加预先存在的着色器
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);

gl.linkProgram(program);

if ( !gl.getProgramParameter( program, gl.LINK_STATUS) ) {
  var info = gl.getProgramInfoLog(program);
  throw 'WebGL program 不能编译. \n\n' + info;
}

查看 WebGLShader api 了解更多关于创建以上例子中的顶点着色器片元着色器的信息。

示例

使用着色器程序

着色器程序在使用的过程中要分为几步,包括告知 GPU 来使用这段着色器程序,绑定合适的数据缓冲区,配置相关选项,最终把图像绘制到屏幕上。

// Use the program
gl.useProgram(program);

// Bind existing attribute data
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.enableVertexAttribArray(attributeLocation);
gl.vertexAttribPointer(attributeLocation, 3, gl.FLOAT, false, 0, 0);

// Draw a single triangle
gl.drawArrays(gl.TRIANGLES, 0, 3);

删除着色器程序

如果在连接着色器程序的过程中发生了错误,或者你希望删除一个已经存在的着色器程序,你可以调用代码 WebGLRenderingContext.deleteProgram(),这将释放连接着色器程序的内存。

gl.deleteProgram(program);

规范

规范 状态 说明
WebGL 1.0
WebGLProgram
Recommendation 初始定义。

浏览器兼容

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
WebGLProgramChrome 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 25Firefox 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 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.

相关链接

文档标签和贡献者

最后编辑者: lovefengruoqing,