这篇翻译不完整。请帮忙从英语翻译这篇文章

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

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 'Could not compile WebGL program. \n\n' + info;
}

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

示例

使用着色器程序

着色器程序实际上做了几个步骤,包括告诉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 AndroidEdge MobileFirefox 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 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.

相关链接

文档标签和贡献者

最后编辑者: mdnwebdocs-bot,