Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. WebGLShader

WebGLShader

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨July 2015⁩.

* Some parts of this feature may have varying levels of support.

Note: This feature is available inWeb Workers.

TheWebGLShader is part of theWebGL API and can either be a vertex or a fragment shader. AWebGLProgram requires both types of shaders.

WebGLObject WebGLShader

Description

To create aWebGLShader useWebGLRenderingContext.createShader, then hook up the GLSL source code usingWebGLRenderingContext.shaderSource(), and finally invokeWebGLRenderingContext.compileShader() to finish and compile the shader. At this point theWebGLShader is still not in a usable form and must still be attached to aWebGLProgram.

js
function createShader(gl, sourceCode, type) {  // Compiles either a shader of type gl.VERTEX_SHADER or gl.FRAGMENT_SHADER  const shader = gl.createShader(type);  gl.shaderSource(shader, sourceCode);  gl.compileShader(shader);  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {    const info = gl.getShaderInfoLog(shader);    throw new Error(`Could not compile WebGL program. \n\n${info}`);  }  return shader;}

SeeWebGLProgram for information on attaching the shaders.

Examples

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.

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

Creating a fragment shader

js
const fragmentShaderSource = `void main() {  gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);}`;// Use the createShader function from the example aboveconst fragmentShader = createShader(  gl,  fragmentShaderSource,  gl.FRAGMENT_SHADER,);

Specifications

Specification
WebGL Specification
# 5.8

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp