/Web APIs


The WebGLShader is part of the WebGL API and can either be a vertex or a fragment shader. A WebGLProgram requires both types of shaders.

WebGLObject WebGLShader


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
  const shader = gl.createShader(type);
  gl.shaderSource(shader, sourceCode);

  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    const info = gl.getShaderInfoLog(shader);
    throw `Could not compile WebGL program. \n\n${info}`;
  return shader;

See 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.

const vertexShaderSource =
  "attribute vec4 position;\n" +
  "void main() {\n" +
  "  gl_Position = position;\n" +

//Use the createShader function from the example above
const vertexShader = createShader(gl, vertexShaderSource, gl.VERTEX_SHADER);

Creating a fragment shader

const 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
const fragmentShader = createShader(


Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
WebGLShader 10 12 4 11 12 5.1 4.4 25 4 12 8 1.5
worker_support No No 105 No No No No No 105 No No No

See also

© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.