Source: https://www.khronos.org/registry/webgl/specs/latest/1.0/
Timestamp: 2019-04-21 03:12:05+00:00

Document:
This specification describes an additional rendering context and support objects for the HTML 5 canvas element [CANVAS]. This context allows rendering using an API that conforms closely to the OpenGL ES 2.0 API.
This document is an editor's draft. Do not cite this document as other than work in progress.
Public discussion of this specification is welcome on the public_webgl@khronos.org mailing list (instructions, archives).
Please file bugs against the specification or its conformance tests in the issue tracker. Pull requests are welcome against the Github repository.
WebGL™ is an immediate mode 3D rendering API designed for the web. It is derived from OpenGL® ES 2.0, and provides similar rendering functionality, but in an HTML context. WebGL is designed as a rendering context for the HTML Canvas element. The HTML Canvas provides a destination for programmatic rendering in web pages, and allows for performing that rendering using different rendering APIs. The only such interface described as part of the Canvas specification is the 2D canvas rendering context, CanvasRenderingContext2D. This document describes another such interface, WebGLRenderingContext, which presents the WebGL API.
The immediate mode nature of the API is a divergence from most web APIs. Given the many use cases of 3D graphics, WebGL chooses the approach of providing flexible primitives that can be applied to any use case. Libraries can provide an API on top of WebGL that is more tailored to specific areas, thus adding a convenience layer to WebGL that can accelerate and simplify development. However, because of its OpenGL ES 2.0 heritage, it should be straightforward for developers familiar with modern desktop OpenGL or OpenGL ES 2.0 development to transition to WebGL development.
Many functions described in this document contain links to OpenGL ES man pages. While every effort is made to make these pages match the OpenGL ES 2.0 specification [GLES20], they may contain errors. In the case of a contradiction, the OpenGL ES 2.0 specification is the final authority.
The remaining sections of this document are intended to be read in conjunction with the OpenGL ES 2.0 specification (2.0.25 at the time of this writing, available from the Khronos OpenGL ES API Registry). Unless otherwise specified, the behavior of each method is defined by the OpenGL ES 2.0 specification. This specification may diverge from OpenGL ES 2.0 in order to ensure interoperability or security, often defining areas that OpenGL ES 2.0 leaves implementation-defined. These differences are summarized in the Differences Between WebGL and OpenGL ES 2.0 section.
Before using the WebGL API, the author must obtain a WebGLRenderingContext object for a given HTMLCanvasElement [CANVAS] or OffscreenCanvas [OFFSCREENCANVAS] as described below. This object is used to manage OpenGL state and render to the drawing buffer, which must be created at the time of context creation.
Each WebGLRenderingContext has an associated canvas, set upon creation, which is a canvas [CANVAS] or offscreen canvas [OFFSCREENCANVAS].
Each WebGLRenderingContext has context creation parameters, set upon creation, in a WebGLContextAttributes object.
Each WebGLRenderingContext has actual context parameters, set each time the drawing buffer is created, in a WebGLContextAttributes object.
Each WebGLRenderingContext has a webgl context lost flag, which is initially unset.
Create a new WebGLRenderingContext object, context.
Let context's canvas be the canvas or offscreen canvas the getContext() method is associated with.
Create a new WebGLContextAttributes object, contextAttributes.
If getContext() was invoked with a second argument, options, set the attributes of contextAttributes from those specified in options.
Create a drawing buffer using the settings specified in contextAttributes, and associate the drawing buffer with context.
Fire a WebGL context creation error at canvas.
Return null and terminate these steps.
Create a new WebGLContextAttributes object, actualAttributes.
Set the attributes of actualAttributes based on the properties of the newly created drawing buffer.
Set context's context creation parameters to contextAttributes.
Set context's actual context parameters to actualAttributes.
The canvas context type 'experimental-webgl' has historically been used to provide access to WebGL implementations which are not yet complete or conformant.
If the user agent supports both the webgl and experimental-webgl canvas context types, they shall be treated as aliases. For example, if a call to getContext('webgl') successfully creates a WebGLRenderingContext, a subsequent call to getContext('experimental-webgl') shall return the same context object.
The drawing buffer into which the API calls are rendered shall be defined upon creation of the WebGLRenderingContext object. The following description defines how to create a drawing buffer.
The table below shows all the buffers which make up the drawing buffer, along with their minimum sizes and whether they are defined or not by default. The size of this drawing buffer shall be determined by the width and height attributes of the HTMLCanvasElement or OffscreenCanvas. The table below also shows the value to which these buffers shall be cleared when first created, when the size is changed, or after presentation when the preserveDrawingBuffer context creation attribute is false.
If the requested width or height cannot be satisfied, either when the drawing buffer is first created or when the width and height attributes of the HTMLCanvasElement or OffscreenCanvas are changed, a drawing buffer with smaller dimensions shall be created. The dimensions actually used are implementation dependent and there is no guarantee that a buffer with the same aspect ratio will be created. The actual drawing buffer size can be obtained from the drawingBufferWidth and drawingBufferHeight attributes.
A WebGL implementation must not perform any automatic scaling of the size of the drawing buffer on high-definition displays. The context's drawingBufferWidth and drawingBufferHeight must match the canvas's width and height attributes as closely as possible, modulo implementation-dependent constraints.
The constraint above does not change the amount of space the canvas element consumes on the web page, even on a high-definition display. The canvas's intrinsic dimensions [CANVAS] equal the size of its coordinate space, with the numbers interpreted in CSS pixels, and CSS pixels are resolution-independent [CSS].
A WebGL application can achieve a 1:1 ratio between drawing buffer pixels and on-screen pixels on high-definition displays by examining properties like window.devicePixelRatio, scaling the canvas's width and height by that factor, and setting its CSS width and height to the original width and height. An application can simulate the effect of running on a higher-resolution display simply by scaling up the canvas's width and height properties.
The optional WebGLContextAttributes object may be used to change whether or not the buffers are defined. It can also be used to define whether the color buffer will include an alpha channel. If defined, the alpha channel is used by the HTML compositor to combine the color buffer with the rest of the page. The WebGLContextAttributes object is only used on the first call to getContext. No facility is provided to change the attributes of the drawing buffer after its creation.
The depth, stencil and antialias attributes, when set to true, are requests, not requirements. The WebGL implementation should make a best effort to honor them. When any of these attributes is set to false, however, the WebGL implementation must not provide the associated functionality. Combinations of attributes not supported by the WebGL implementation or graphics hardware shall not cause a failure to create a WebGLRenderingContext. The actual context parameters are set to the attributes of the created drawing buffer. The alpha, premultipliedAlpha and preserveDrawingBuffer attributes must be obeyed by the WebGL implementation.
Before the drawing buffer is presented for compositing the implementation shall ensure that all rendering operations have been flushed to the drawing buffer. By default, after compositing the contents of the drawing buffer shall be cleared to their default values, as shown in the table above.
This default behavior can be changed by setting the preserveDrawingBuffer attribute of the WebGLContextAttributes object. If this flag is true, the contents of the drawing buffer shall be preserved until the author either clears or overwrites them. If this flag is false, attempting to perform operations using this context as a source image after the rendering function has returned can lead to undefined behavior. This includes readPixels or toDataURL calls, using this context as the source image of another context's texImage2D or drawImage call, or creating an ImageBitmap [HTML] from this context's canvas.
While it is sometimes desirable to preserve the drawing buffer, it can cause significant performance loss on some platforms. Whenever possible this flag should remain false and other techniques used. Techniques like synchronous drawing buffer access (e.g., calling readPixels or toDataURL in the same function that renders to the drawing buffer) can be used to get the contents of the drawing buffer. If the author needs to render to the same drawing buffer over a series of calls, a Framebuffer Object can be used.
Implementations may optimize away the required implicit clear operation of the Drawing Buffer as long as a guarantee can be made that the author cannot gain access to buffer contents from another process. For instance, if the author performs an explicit clear then the implicit clear is not needed.
OpenGL manages a rectangular viewport as part of its state which defines the placement of the rendering results in the drawing buffer. Upon creation of WebGL context context, the viewport is initialized to a rectangle with origin at (0, 0) and width and height equal to (context.drawingBufferWidth, context.drawingBufferHeight).
A WebGL implementation shall not affect the state of the OpenGL viewport in response to resizing of the canvas element.
Note that if a WebGL program does not contain logic to set the viewport, it will not properly handle the case where the canvas is resized. The following ECMAScript example illustrates how a WebGL program might resize the canvas programmatically.
Rationale: automatically setting the viewport will interfere with applications that set it manually. Applications are expected to use onresize handlers to respond to changes in size of the canvas and set the OpenGL viewport in turn.
The OpenGL API allows the application to modify the blending modes used during rendering, and for this reason allows control over how alpha values in the drawing buffer are interpreted; see the premultipliedAlpha parameter in the WebGLContextAttributes section.
The HTML Canvas APIs toDataURL and drawImage must respect the premultipliedAlpha context creation parameter. When toDataURL is called against a Canvas into which WebGL content is being rendered, then if the requested image format does not specify premultiplied alpha and the WebGL context has the premultipliedAlpha parameter set to true, then the pixel values must be de-multiplied; i.e., the color channels are divided by the alpha channel. Note that this operation is lossy.
Passing a WebGL-rendered Canvas to the drawImage method of CanvasRenderingContext2D may or may not need to modify the the rendered WebGL content during the drawing operation, depending on the premultiplication needs of the CanvasRenderingContext2D implementation.
When passing a WebGL-rendered Canvas to the texImage2D API, then depending on the setting of the premultipliedAlpha context creation parameter of the passed canvas and the UNPACK_PREMULTIPLY_ALPHA_WEBGL pixel store parameter of the destination WebGL context, the pixel data may need to be changed to or from premultiplied form.
WebGL resources such as textures and vertex buffer objects (VBOs) must always contain initialized data, even if they were created without initial user data values. Creating a resource without initial values is commonly used to reserve space for a texture or VBO, which is then modified using texSubImage or bufferSubData calls. If initial data is not provided to these calls, the WebGL implementation must initialize their contents to 0; depth resources must be cleared to the default 1.0 clear depth. This may require creating a zeroed temporary buffer the size of a requested VBO, so that it can be initialized correctly. All other forms of loading data into a texture or VBO involve either ArrayBuffers or DOM objects such as images, and are therefore already required to be initialized.
When WebGL resources are accessed by shaders through a call such as drawElements or drawArrays, the WebGL implementation must ensure that the shader cannot access either out of bounds or uninitialized data. See Enabled Vertex Attributes and Range Checking for restrictions which must be enforced by the WebGL implementation.
If the texImage2D or texSubImage2D method is called with otherwise correct arguments and an HTMLImageElement, HTMLVideoElement, HTMLCanvasElement, or ImageBitmap violating these restrictions, a SECURITY_ERR exception must be thrown.
WebGL necessarily imposes stronger restrictions on the use of cross-domain media than other APIs such as the 2D canvas rendering context, because shaders can be used to indirectly deduce the contents of textures which have been uploaded to the GPU.
WebGL applications may utilize images and videos that come from other domains, with the cooperation of the server hosting the media, using Cross-Origin Resource Sharing [CORS]. In order to use such media, the application needs to explicitly request permission to do so, and the server needs to explicitly grant permission. Successful CORS-enabled fetches of image and video elements from other domains cause the origin of these elements to be set to that of the containing Document [HTML].
The following ECMAScript example demonstrates how to issue a CORS request for an image coming from another domain. The image is fetched from the server without any credentials, i.e., cookies.
// using texImage2D or texSubImage2D.
Note that these rules imply that the origin-clean flag for a canvas rendered using WebGL will never be set to false.
A shader referencing state variables or functions that are available in other versions of GLSL, such as that found in versions of OpenGL for the desktop, must not be allowed to load.
for loops must conform to the structural constraints in Appendix A.
while and do-while loops are disallowed, since they are optional in Appendix A.
Appendix A mandates certain forms of indexing of arrays; for example, within fragment shaders, indexing is only mandated with a constant-index-expression (see [GLES20GLSL] for the definition of this term). In the WebGL API, only the forms of indexing mandated in Appendix A are supported.
In addition to the reserved identifiers in the aforementioned specification, identifiers starting with "webgl_" and "_webgl_" are reserved for use by WebGL. A shader which declares a function, variable, structure name, or structure field starting with these prefixes must not be allowed to load.
It is possible to create, either intentionally or unintentionally, combinations of shaders and geometry that take an undesirably long time to render. This issue is analogous to that of long-running scripts, for which user agents already have safeguards. However, long-running draw calls can cause loss of interactivity for the entire window system, not just the user agent.
In the general case it is not possible to impose limits on the structure of incoming shaders to guard against this problem. Experimentation has shown that even very strict structural limits are insufficient to prevent long rendering times, and such limits would prevent shader authors from implementing common algorithms.
Splitting up draw calls with large numbers of elements into smaller draw calls.
Timing individual draw calls and forbidding further rendering from a page if a certain timeout is exceeded.
Using any watchdog facilities available at the user level, graphics API level, or operating system level to limit the duration of draw calls.
Separating the graphics rendering of the user agent into a distinct operating system process which can be terminated and restarted without losing application state.
The supporting infrastructure at the OS and graphics API layer is expected to improve over time, which is why the exact nature of these safeguards is not specified.
Values from anywhere within the storage accessible to the program.
Out-of-range writes are either discarded or modify an unspecified value in the storage accessible to the program.
This behavior replicates that defined in [KHRROBUSTACCESS].
See Supported GLSL Constructs for more information on restrictions which simplify static analysis of the array indexing operations in shaders.
This section describes the interfaces and functionality added to the DOM to support runtime access to the functionality described above.
The following types are used in all interfaces in the following section.
// Ideally the typedef below would use 'unsigned byte', but that doesn't currently exist in Web IDL.
// section of the specification.
The WebGLContextAttributes dictionary contains drawing surface attributes and is passed as the second parameter to getContext.
The following list describes each attribute in the WebGLContextAttributes object and its use. The default value for each attribute is shown above. The default value is used either if no second parameter is passed to getContext, or if a user object is passed which has no attribute of the given name.
If the value is true, the drawing buffer has an alpha channel for the purposes of performing OpenGL destination alpha operations and compositing with the page. If the value is false, no alpha buffer is available.
If the value is true, the drawing buffer has a depth buffer of at least 16 bits. If the value is false, no depth buffer is available.
If the value is true, the drawing buffer has a stencil buffer of at least 8 bits. If the value is false, no stencil buffer is available.
If the value is true and the implementation supports antialiasing the drawing buffer will perform antialiasing using its choice of technique (multisample/supersample) and quality. If the value is false or the implementation does not support antialiasing, no antialiasing is performed.
If the value is true the page compositor will assume the drawing buffer contains colors with premultiplied alpha. If the value is false the page compositor will assume that colors in the drawing buffer are not premultiplied. This flag is ignored if the alpha flag is false. See Premultiplied Alpha for more information on the effects of the premultipliedAlpha flag.
If false, once the drawing buffer is presented as described in theDrawing Buffer section, the contents of the drawing buffer are cleared to their default values. All elements of the drawing buffer (color, depth and stencil) are cleared. If the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author.
On some hardware setting the preserveDrawingBuffer flag to true can have significant performance implications.
Provides a hint to the user agent indicating what configuration of GPU is suitable for this WebGL context. This may influence which GPU is used in a system with multiple GPUs. For example, a dual-GPU system might have one GPU that consumes less power at the expense of rendering performance. Note that this property is only a hint and a WebGL implementation may choose to ignore it.
WebGL implementations use context lost and restored events to regulate power and memory consumption, regardless of the value of this attribute. At WebGLRenderingContext creation time, this attribute will be ignored if no event listeners exist which would handle both "webglcontextlost" and "webglcontextrestored" events dispatched to the canvas element.
Let the user agent decide which GPU configuration is most suitable. This is the default value.
Indicates a request for a GPU configuration that prioritizes rendering performance over power consumption. Any content that chooses this value should be aware that it is more likely that the user agent will force a lost context at any time. Implementations may decide to initially respect this request and, after some time, lose the context and restore a new context ignoring the request. Developers are encouraged to only specify this value if they believe it is absolutely necessary, since it may significantly decrease battery life on mobile devices.
Indicates a request for a GPU configuration that prioritizes power saving over rendering performance. Generally, content should use this if it is unlikely to be constrained by drawing performance; for example, if it renders only one frame per second, draws only relatively simple geometry with simple shaders, or uses a small HTML canvas element. Developers are encouraged to use this value if their content allows, since it may significantly improve battery life on mobile devices.
An implementation might switch to a software rasterizer if the user's GPU driver is known to be unstable.
An implementation might require reading back the framebuffer from GPU memory to system memory before compositing it with the rest of the page, significantly reducing performance.
Applications that don't require high performance should leave this parameter at its default value of false. Applications that require high performance may set this parameter to true, and if context creation fails then the application may prefer to use a fallback rendering path such as a 2D canvas context. Alternatively the application can retry WebGL context creation with this parameter set to false, with the knowledge that a reduced-fidelity rendering mode should be used to improve performance.
If the value is true, then the user agent may optimize the rendering of the canvas to reduce the latency, as measured from input events to rasterization, by desynchronizing the canvas paint cycle from the event loop, bypassing the ordinary user agent rendering algorithm, or both. Insofar as this mode involves bypassing the usual paint mechanisms, rasterization, or both, it might introduce visible tearing artifacts.
The desynchronized boolean can be useful when implementing certain kinds of applications, such as drawing applications, where the latency between input and rasterization is critical.
Here is an ECMAScript example which passes a WebGLContextAttributes argument to getContext. It assumes the presence of a canvas element named "canvas1" on the page.
Each WebGLObject has an invalidated flag, which is initially unset.
The WebGLBuffer interface represents an OpenGL Buffer Object. The underlying object is created as if by calling glGenBuffers (OpenGL ES 2.0 §2.9, man page) , bound as if by calling glBindBuffer (OpenGL ES 2.0 §2.9, man page) and marked for deletion as if by calling glDeleteBuffers (OpenGL ES 2.0 §2.9, man page) .
The WebGLFramebuffer interface represents an OpenGL Framebuffer Object. The underlying object is created as if by calling glGenFramebuffers (OpenGL ES 2.0 §4.4.1, man page) , bound as if by calling glBindFramebuffer (OpenGL ES 2.0 §4.4.1, man page) and marked for deletion as if by calling glDeleteFramebuffers (OpenGL ES 2.0 §4.4.1, man page) .
The WebGLProgram interface represents an OpenGL Program Object. The underlying object is created as if by calling glCreateProgram (OpenGL ES 2.0 §2.10.3, man page) , used as if by calling glUseProgram (OpenGL ES 2.0 §2.10.3, man page) and marked for deletion as if by calling glDeleteProgram (OpenGL ES 2.0 §2.10.3, man page) .
The WebGLRenderbuffer interface represents an OpenGL Renderbuffer Object. The underlying object is created as if by calling glGenRenderbuffers (OpenGL ES 2.0 §4.4.3, man page) , bound as if by calling glBindRenderbuffer (OpenGL ES 2.0 §4.4.3, man page) and marked for deletion as if by calling glDeleteRenderbuffers (OpenGL ES 2.0 §4.4.3, man page) .
The WebGLShader interface represents an OpenGL Shader Object. The underlying object is created as if by calling glCreateShader (OpenGL ES 2.0 §2.10.1, man page) , attached to a Program as if by calling glAttachShader (OpenGL ES 2.0 §2.10.3, man page) and marked for deletion as if by calling glDeleteShader (OpenGL ES 2.0 §2.10.1, man page) .
The WebGLTexture interface represents an OpenGL Texture Object. The underlying object is created as if by calling glGenTextures (OpenGL ES 2.0 §3.7.13, man page) , bound as if by calling glBindTexture (OpenGL ES 2.0 §3.7.13, man page) and marked for deletion as if by calling glDeleteTextures (OpenGL ES 2.0 §3.7.13, man page) .
The WebGLUniformLocation interface represents the location of a uniform variable in a shader program.
The WebGLActiveInfo interface represents the information returned from the getActiveAttrib and getActiveUniform calls.
The size of the requested variable.
The data type of the requested variable.
The name of the requested variable.
The WebGLShaderPrecisionFormat interface represents the information returned from the getShaderPrecisionFormat call.
Vertex, index, texture, and other data is transferred to the WebGL implementation using ArrayBuffers, Typed Arrays and DataViews as defined in the ECMAScript specification [ECMASCRIPT].
Typed Arrays support the creation of interleaved, heterogeneous vertex data; uploading of distinct blocks of data into a large vertex buffer object; and most other use cases required by OpenGL programs.
Here is an ECMAScript example showing access to the same ArrayBuffer using different types of typed arrays. In this case the buffer contains a floating point vertex position (x, y, z) followed by a color as 4 unsigned bytes (r, g, b, a).
The WebGLRenderingContext represents the API allowing OpenGL ES 2.0 style rendering into the canvas element.
If the [WebGLHandlesContextLoss] extended attribute appears on the called method, perform the implementation of the called method, return its result and terminate these steps.
Let use default return value be false.
If the webgl context lost flag is set, let use default return value be true.
Otherwise, if any argument to the method is a WebGLObject with its invalidated flag set, generate an INVALID_OPERATION error and let use default return value be true.
If the return type of the called method is any or any nullable type, return null.
Terminate this algorithm without calling the method implementation.
Otherwise, perform the implementation of the called method and return its result.
See the context lost event for further details.
A reference to the canvas element or OffscreenCanvas object which created this context.
The actual width of the drawing buffer. May be different from the width attribute of the HTMLCanvasElement if the implementation is unable to satisfy the requested widthor height.
The actual height of the drawing buffer. May be different from the height attribute of the HTMLCanvasElement if the implementation is unable to satisfy the requested width or height.
If the webgl context lost flag is set, returns null. Otherwise, returns a copy of the actual context parameters.
OpenGL ES 2.0 maintains state values for use in rendering. All the calls in this group behave identically to their OpenGL counterparts unless otherwise noted.
See Blending With Constant Color for limitations imposed by WebGL.
depth value is clamped to the range 0 to 1.
zNear and zFar values are clamped to the range 0 to 1 and zNear must be less than or equal to zFar; see Viewport Depth Range.
All queries returning sequences or typed arrays return a new object each time.
If pname is not in the table above, generates an INVALID_ENUM error and returns null.
If pname is IMPLEMENTATION_COLOR_READ_FORMAT or IMPLEMENTATION_COLOR_READ_TYPE, and the currently bound framebuffer is not framebuffer complete, generates an INVALID_OPERATION error and returns null.
VERSION Returns a version or release number of the form WebGL<space>1.0<optional><space><vendor-specific information></optional>.
SHADING_LANGUAGE_VERSION Returns a version or release number of the form WebGL<space>GLSL<space>ES<space>1.0<optional><space><vendor-specific information></optional>.
VENDOR Returns the company responsible for this WebGL implementation. This name does not change from release to release.
RENDERER Returns the name of the renderer. This name is typically specific to a particular configuration of a hardware platform. It does not change from release to release.
See Extension Queries for information on querying the available extensions in the current WebGL implementation.
If the context's webgl context lost flag is set, returns CONTEXT_LOST_WEBGL the first time this method is called. Afterward, returns NO_ERROR until the context has been restored.
For any isEnabled query, the same boolean value can be obtained via getParameter.
Returns false if the context's webgl context lost flag is set.
See NaN Line Width for restrictions specified for WebGL.
In addition to the parameters in the OpenGL ES 2.0 specification, the WebGL specification accepts the parameters UNPACK_FLIP_Y_WEBGL, UNPACK_PREMULTIPLY_ALPHA_WEBGL and UNPACK_COLORSPACE_CONVERSION_WEBGL. See Pixel Storage Parameters for documentation of these parameters.
See Stencil Separate Mask and Reference Value for information on WebGL specific limitations to the allowable argument values.
See Stencil Separate Mask and Reference Value for information on WebGL specific limitations to the allowable mask values.
Drawing commands can only modify pixels inside the currently bound framebuffer. In addition, the viewport and the scissor box affect drawing.
The viewport specifies the affine transformation of x and y from normalized device coordinates to window coordinates. The size of the viewport is initially determined as specified in section The WebGL Viewport. The scissor box defines a rectangle which constrains drawing. When the scissor test is enabled only pixels that lie within the scissor box can be modified by drawing commands including clear, and primitives can only be drawn inside the intersection of the viewport, the currently bound framebuffer, and the scissor box. When the scissor test is not enabled primitives can only be drawn inside the intersection of the viewport and the currently bound framebuffer.
Buffer objects (sometimes referred to as VBOs) hold vertex attribute data for the GLSL shaders.
If buffer was generated by a different WebGLRenderingContext than this one, generates an INVALID_OPERATION error.
Binds the given WebGLBuffer object to the given binding point (target), either ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER. If the buffer is null then any buffer currently bound to this target is unbound. A given WebGLBuffer object may only be bound to one of the ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER target in its lifetime. An attempt to bind a buffer object to the other target will generate an INVALID_OPERATION error, and the current binding will remain untouched. An attempt to bind an object marked for deletion will generate an INVALID_OPERATION error, and the current binding will remain untouched.
Set the size of the currently bound WebGLBuffer object for the passed target. The buffer is initialized to 0.
Set the size of the currently bound WebGLBuffer object for the passed target to the size of the passed data, then write the contents of data to the buffer object.
If the passed data is null then an INVALID_VALUE error is generated.
For the WebGLBuffer object bound to the passed target write the passed data starting at the passed offset. If the data would be written past the end of the buffer object an INVALID_VALUE error is generated. If data is null then an INVALID_VALUE error is generated.
Create a WebGLBuffer object and initialize it with a buffer object name as if by calling glGenBuffers.
Mark for deletion the buffer object contained in the passed WebGLBuffer, as if by calling glDeleteBuffers. If the object has already been marked for deletion, the call has no effect. Note that underlying GL object will be automatically marked for deletion when the JS object is destroyed, however this method allows authors to mark an object for deletion early.
If pname is not in the table above, generates an INVALID_ENUM error.
If an OpenGL error is generated, returns null.
Return true if the passed WebGLBuffer is valid and false otherwise.
Returns false if the buffer was generated by a different WebGLRenderingContext than this one.
Returns false if the buffer's invalidated flag is set.
Framebuffer objects provide an alternative rendering target to the drawing buffer. They are a collection of color, alpha, depth and stencil buffers and are often used to render an image that will later be used as a texture.
If framebuffer was generated by a different WebGLRenderingContext than this one, generates an INVALID_OPERATION error.
Bind the given WebGLFramebuffer object to the given binding point (target), which must be FRAMEBUFFER. If framebuffer is null, the default framebuffer provided by the context is bound and attempts to modify or query state on target FRAMEBUFFER will generate an INVALID_OPERATION error. An attempt to bind an object marked for deletion will generate an INVALID_OPERATION error, and the current binding will remain untouched.
Returns FRAMEBUFFER_UNSUPPORTED if the context's webgl context lost flag is set.
Create a WebGLFramebuffer object and initialize it with a framebuffer object name as if by calling glGenFramebuffers.
Mark for deletion the framebuffer object contained in the passed WebGLFramebuffer, as if by calling glDeleteFramebuffers. If the object has already been marked for deletion, the call has no effect. Note that underlying GL object will be automatically marked for deletion when the JS object is destroyed, however this method allows authors to mark an object for deletion early.
If renderbuffer was generated by a different WebGLRenderingContext than this one, generates an INVALID_OPERATION error.
If texture was generated by a different WebGLRenderingContext than this one, generates an INVALID_OPERATION error.
Return true if the passed WebGLFramebuffer is valid and false otherwise.
Returns false if the framebuffer was generated by a different WebGLRenderingContext than this one.
Returns false if the framebuffer's invalidated flag is set.
Renderbuffer objects are used to provide storage for the individual buffers used in a framebuffer object.
Bind the given WebGLRenderbuffer object to the given binding point (target), which must be RENDERBUFFER. If renderbuffer is null the renderbuffer object currently bound to this target is unbound. An attempt to bind an object marked for deletion will generate an INVALID_OPERATION error, and the current binding will remain untouched.
Create a WebGLRenderbuffer object and initialize it with a renderbuffer object name as if by calling glGenRenderbuffers.
Mark for deletion the renderbuffer object contained in the passed WebGLRenderbuffer, as if by calling glDeleteRenderbuffers. If the object has already been marked for deletion, the call has no effect. Note that underlying GL object will be automatically marked for deletion when the JS object is destroyed, however this method allows authors to mark an object for deletion early.
Return true if the passed WebGLRenderbuffer is valid and false otherwise.
Returns false if the renderbuffer was generated by a different WebGLRenderingContext than this one.
Returns false if the renderbuffer's invalidated flag is set.
Texture objects provide storage and state for texturing operations. If no WebGLTexture is bound (e.g., passing null or 0 to bindTexture) then attempts to modify or query the texture object shall generate an INVALID_OPERATION error. This is indicated in the functions below.
An attempt to bind an object marked for deletion will generate an INVALID_OPERATION error, and the current binding will remain untouched.
If an attempt is made to call these functions with no WebGLTexture bound (see above), an INVALID_OPERATION error is generated.
The core WebGL specification does not define any supported compressed texture formats. By default, these methods generate an INVALID_ENUM error and return immediately. See Compressed Texture Support.
If an attempt is made to call this function with no WebGLTexture bound (see above), an INVALID_OPERATION error is generated.
For any pixel lying outside the frame buffer, all channels of the associated texel are initialized to 0; see Reading Pixels Outside the Framebuffer.
If this function attempts to read from a complete framebuffer with a missing attachment, an INVALID_OPERATION error is generated per Reading from a Missing Attachment.
For any pixel lying outside the frame buffer, the corresponding destination pixel remains untouched; see Reading Pixels Outside the Framebuffer.
Create a WebGLTexture object and initialize it with a texture object name as if by calling glGenTextures.
Mark for deletion the texture object contained in the passed WebGLTexture, as if by calling glDeleteTextures. If the object has already been marked for deletion, the call has no effect. Note that underlying GL object will be automatically marked for deletion when the JS object is destroyed, however this method allows authors to mark an object for deletion early.
If an attempt is made to call this function with no WebGLTexture bound (see above), generates an INVALID_OPERATION error.
Return true if the passed WebGLTexture is valid and false otherwise.
Returns false if the texture was generated by a different WebGLRenderingContext than this one.
Returns false if the texture's invalidated flag is set.
If pixels is null, a buffer of sufficient size initialized to 0 is passed.
If pixels is non-null, the type of pixels must match the type of the data to be read. If it is UNSIGNED_BYTE, a Uint8Array must be supplied; if it is UNSIGNED_SHORT_5_6_5, UNSIGNED_SHORT_4_4_4_4, or UNSIGNED_SHORT_5_5_5_1, a Uint16Array must be supplied. If the types do not match, an INVALID_OPERATION error is generated.
See Pixel Storage Parameters for WebGL-specific pixel storage parameters that affect the behavior of this function.
If pixels is non-null but its size is less than what is required by the specified width, height, format, type, and pixel storage parameters, generates an INVALID_OPERATION error.
Uploads the given element or image data to the currently bound WebGLTexture.
The width and height of the texture are set as specified in section Texture Upload Width and Height.
The source image data is conceptually first converted to the data type and format specified by the format and type arguments, and then transferred to the WebGL implementation. Format conversion is performed according to the following table. If a packed pixel format is specified which would imply loss of bits of precision from the image data, this loss of precision must occur.
See Pixel Storage Parameters for WebGL-specific pixel storage parameters that affect the behavior of this function when it is called with any argument type other than ImageBitmap.
The first pixel transferred from the source to the WebGL implementation corresponds to the upper left corner of the source. This behavior is modified by the UNPACK_FLIP_Y_WEBGL pixel storage parameter, except for ImageBitmap arguments, as described in the abovementioned section.
If the source is an HTMLImageElement or ImageBitmap containing an RGB or RGBA lossless image with 8 bits per channel, the browser guarantees that the full precision of all channels is preserved.
If the original HTMLImageElement contains an alpha channel and the UNPACK_PREMULTIPLY_ALPHA_WEBGL pixel storage parameter is false, then the RGB values are guaranteed to never have been premultiplied by the alpha channel, whether those values are derived directly from the original file format or converted from some other color format.
Some implementations of HTMLCanvasElement's or OffscreenCanvas's CanvasRenderingContext2D store color values internally in premultiplied form. If such a canvas is uploaded to a WebGL texture with the UNPACK_PREMULTIPLY_ALPHA_WEBGL pixel storage parameter set to false, the color channels will have to be un-multiplied by the alpha channel, which is a lossy operation. The WebGL implementation therefore can not guarantee that colors with alpha < 1.0 will be preserved losslessly when first drawn to a canvas via CanvasRenderingContext2D and then uploaded to a WebGL texture when the UNPACK_PREMULTIPLY_ALPHA_WEBGL pixel storage parameter is set to false.
If this function is called with an ImageData whose data attribute has been neutered, an INVALID_VALUE error is generated.
If this function is called with an ImageBitmap that has been neutered, an INVALID_VALUE error is generated.
If this function is called with an HTMLImageElement or HTMLVideoElement whose origin differs from the origin of the containing Document, or with an HTMLCanvasElement, ImageBitmap or OffscreenCanvas whose bitmap's origin-clean flag is set to false, a SECURITY_ERR exception must be thrown. See Origin Restrictions.
If source is null then an INVALID_VALUE error is generated.
See texImage2D for restrictions on the format and pixels arguments.
If type does not match the type originally used to define the texture, an INVALID_OPERATION error is generated.
If pixels is null then an INVALID_VALUE error is generated.
Updates a sub-rectangle of the currently bound WebGLTexture with the contents of the given element or image data.
The width and height of the updated sub-rectangle are determined as specified in section Texture Upload Width and Height.
See texImage2D for the interpretation of the format and type arguments, and notes on the UNPACK_PREMULTIPLY_ALPHA_WEBGL pixel storage parameter.
If this function is called with an HTMLImageElement or HTMLVideoElement whose origin differs from the origin of the containing Document, or with an HTMLCanvasElement, ImageBitmap, or OffscreenCanvas whose bitmap's origin-clean flag is set to false, a SECURITY_ERR exception must be thrown. See Origin Restrictions.
Rendering with OpenGL ES 2.0 requires the use of shaders, written in OpenGL ES's shading language, GLSL ES. Shaders must be loaded with a source string (shaderSource), compiled (compileShader) and attached to a program (attachShader) which must be linked (linkProgram) and then used (useProgram).
If either program or shader were generated by a different WebGLRenderingContext than this one, generates an INVALID_OPERATION error.
If program was generated by a different WebGLRenderingContext than this one, generates an INVALID_OPERATION error.
If the passed name is longer than the restriction defined in Maximum Uniform and Attribute Location Lengths, generates an INVALID_VALUE error.
If name starts with one of the reserved WebGL prefixes per GLSL Constructs, generates an INVALID_OPERATION error.
See Characters Outside the GLSL Source Character Set for additional validation performed by WebGL implementations.
If shader was generated by a different WebGLRenderingContext than this one, generates an INVALID_OPERATION error.
See Supported GLSL Constructs, Maximum GLSL Token Size, Characters Outside the GLSL Source Character Set, Maximum Nesting of Structures in GLSL Shaders, and Packing Restrictions for Uniforms and Varyings for additional constraints enforced in, additional constructs supported by, and additional validation performed by WebGL implementations.
Create a WebGLProgram object and initialize it with a program object name as if by calling glCreateProgram.
Create a WebGLShader object and initialize it with a shader object name as if by calling glCreateShader.
Mark for deletion the program object contained in the passed WebGLProgram, as if by calling glDeleteProgram. If the object has already been marked for deletion, the call has no effect. Note that underlying GL object will be automatically marked for deletion when the JS object is destroyed, however this method allows authors to mark an object for deletion early.
Mark for deletion the shader object contained in the passed WebGLShader, as if by calling glDeleteShader. If the object has already been marked for deletion, the call has no effect. Note that underlying GL object will be automatically marked for deletion when the JS object is destroyed, however this method allows authors to mark an object for deletion early.
Returns a new object representing the list of shaders attached to the passed program.
Returns null if any OpenGL errors are generated during the execution of this function.
Return a new WebGLShaderPrecisionFormat describing the range and precision for the specified shader numeric format. The shadertype value can be FRAGMENT_SHADER or VERTEX_SHADER. The precisiontype value can be LOW_FLOAT, MEDIUM_FLOAT, HIGH_FLOAT, LOW_INT, MEDIUM_INT or HIGH_INT.
Return true if the passed WebGLProgram is valid and false otherwise.
Returns false if the program was generated by a different WebGLRenderingContext than this one.
Returns false if the program's invalidated flag is set.
Return true if the passed WebGLShader is valid and false otherwise.
Returns false if the shader was generated by a different WebGLRenderingContext than this one.
Returns false if the shader's invalidated flag is set.
Links the passed program object. Details of the behavior are defined in the OpenGL ES 2.0 specification, with the following clarifications: linkProgram is the only API in this group which affects the passed program's link status, and the internal executable code it references. Operations like attaching and detaching shader objects from a program, modifying shader objects which are attached to a program, or compiling shader objects attached to a program affect neither that program's link status, nor the executable code that program may reference.
If the given program is linked successfully and is also the current program object in use as defined by useProgram, below, then the generated executable code will be immediately installed as part of the current rendering state. Otherwise any executable code referenced by the current rendering state is unmodified by a call to linkProgram.
See Packing Restrictions for Uniforms and Varyings for additional constraints enforced in, and additional validation performed by, WebGL implementations.
Values used by the shaders are passed in as uniforms or vertex attributes.
Enable the vertex attribute at index as an array. WebGL imposes additional rules beyond OpenGL ES 2.0 regarding enabled vertex attributes; see Enabled Vertex Attributes and Range Checking.
Returns a new WebGLActiveInfo object describing the size, type and name of the vertex attribute at the passed index of the passed program object. If the passed index is out of range, generates an INVALID_VALUE error and returns null.
Returns a new WebGLActiveInfo object describing the size, type and name of the uniform at the passed index of the passed program object. If the passed index is out of range, generates an INVALID_VALUE error and returns null.
If program was generated by a different WebGLRenderingContext than this one, generates an INVALID_OPERATION error and returns -1.
If the passed name is longer than the restriction defined in Maximum Uniform and Attribute Location Lengths, generates an INVALID_VALUE error and returns -1.
Returns -1 if name starts with one of the reserved WebGL prefixes per GLSL Constructs.
Returns -1 if the context's webgl context lost flag is set.
If the invalidated flag of the passed program is set, generates an INVALID_OPERATION error and returns -1.
If either program or location were generated by a different WebGLRenderingContext than this one, generates an INVALID_OPERATION error.
Return a new WebGLUniformLocation that represents the location of a specific uniform variable within a program object. The return value is null if name does not correspond to an active uniform variable in the passed program.
If the passed name is longer than the restriction defined in Maximum Uniform and Attribute Location Lengths, generates an INVALID_VALUE error and returns null.
Returns null if name starts with one of the reserved WebGL prefixes per GLSL Constructs.
Returns 0 if the context's webgl context lost flag is set.
Each of the uniform* functions above sets the specified uniform or uniforms to the values provided. If the passed location is not null and was not obtained from the currently used program via an earlier call to getUniformLocation, an INVALID_OPERATION error will be generated. If the passed location is null, the data passed in will be silently ignored and no uniform variables will be changed.
If the array passed to any of the vector forms (those ending in v) has an invalid length, an INVALID_VALUE error will be generated. The length is invalid if it is too short for or is not an integer multiple of the assigned type.
Performance problems have been observed on some implementations when using uniform1i to update sampler uniforms. To change the texture referenced by a sampler uniform, binding a new texture to the texture unit referenced by the uniform should be preferred over using uniform1i to update the uniform itself.
Sets the vertex attribute at the passed index to the given constant value. Values set via the vertexAttrib are guaranteed to be returned from the getVertexAttrib function with the CURRENT_VERTEX_ATTRIB param, even if there have been intervening calls to drawArrays or drawElements.
If the array passed to any of the vector forms (those ending in v) is too short, an INVALID_VALUE error will be generated.
Assign the WebGLBuffer object currently bound to the ARRAY_BUFFER target to the vertex attribute at the passed index. Size is number of components per attribute. Stride and offset are in units of bytes. Passed stride and offset must be appropriate for the passed type and size or an INVALID_OPERATION error will be generated; see Buffer Offset and Stride Requirements. If offset is negative, an INVALID_VALUE error will be generated. If no WebGLBuffer is bound to the ARRAY_BUFFER target and offset is non-zero, an INVALID_OPERATION error will be generated. In WebGL, the maximum supported stride is 255; see Vertex Attribute Data Stride.
OpenGL ES 2.0 has 3 calls which can render to the drawing buffer: clear, drawArrays and drawElements. Furthermore rendering can be directed to the drawing buffer or to a Framebuffer object. When rendering is directed to the drawing buffer, making any of the 3 rendering calls shall cause the drawing buffer to be presented to the HTML page compositor at the start of the next compositing operation.
If any one of these 3 calls attempts to draw to a missing attachment of a complete framebuffer, nothing is drawn to that attachment and no error is generated per Drawing to a Missing Attachment.
If first is negative, an INVALID_VALUE error will be generated. If the CURRENT_PROGRAM is null, an INVALID_OPERATION error will be generated.
Draw using the currently bound element array buffer. The given offset is in bytes, and must be a valid multiple of the size of the given type or an INVALID_OPERATION error will be generated; in addition the offset must be non-negative or an INVALID_VALUE error will be generated; see Buffer Offset and Stride Requirements. If count is greater than zero, then a non-null WebGLBuffer must be bound to the ELEMENT_ARRAY_BUFFER binding point or an INVALID_OPERATION error will be generated.
If the CURRENT_PROGRAM is null, an INVALID_OPERATION error will be generated. WebGL performs additional error checking beyond that specified in OpenGL ES 2.0 during calls to drawArrays and drawElements. See Enabled Vertex Attributes and Range Checking.
Pixels in the current framebuffer can be read back into an ArrayBufferView object.
Fills pixels with the pixel data in the specified rectangle of the frame buffer. The data returned from readPixels must be up-to-date as of the most recently sent drawing command.
The type of pixels must match the type of the data to be read. For example, if it is UNSIGNED_BYTE, a Uint8Array must be supplied; if it is UNSIGNED_SHORT_5_6_5, UNSIGNED_SHORT_4_4_4_4, or UNSIGNED_SHORT_5_5_5_1, a Uint16Array must be supplied; if it is FLOAT, a Float32Array must be supplied. If the types do not match, an INVALID_OPERATION error is generated.
Only two combinations of format and type are accepted. The first is format RGBA and type UNSIGNED_BYTE. The second is an implementation-chosen format. The values of format and type for this format may be determined by calling getParameter with the symbolic constants IMPLEMENTATION_COLOR_READ_FORMAT and IMPLEMENTATION_COLOR_READ_TYPE, respectively. The implementation-chosen format may vary depending on the format of the currently bound rendering surface. Unsupported combinations of format and type will generate an INVALID_OPERATION error.
Because queries of IMPLEMENTATION_COLOR_READ_[FORMAT,TYPE] may return enums not used elsewhere, providing these enums to readPixels will not necessarily generate INVALID_ENUM.
If pixels is null, an INVALID_VALUE error is generated. If pixels is non-null, but is not large enough to retrieve all of the pixels in the specified rectangle taking into account pixel store modes, an INVALID_OPERATION error is generated.
For any pixel lying outside the frame buffer, the corresponding destination buffer range remains untouched; see Reading Pixels Outside the Framebuffer.
If this function attempts to read from a complete framebuffer with a missing color attachment, an INVALID_OPERATION error is generated per Reading from a Missing Attachment.
Occurrences such as power events on mobile devices may cause the WebGL rendering context to be lost at any time and require the application to rebuild it; see WebGLContextEvent for more details. The following method assists in detecting context lost events.
Return true if the webgl context lost flag is set, otherwise return false.
An implementation of WebGL must not support any additional parameters, constants or functions without first enabling that functionality through the extension mechanism. The getSupportedExtensions function returns an array of the extension strings supported by this implementation. An extension is enabled by passing one of those strings to the getExtension function. This call returns an object which contains any constants or functions defined by that extension. The definition of that object is specific to the extension and must be defined by the extension specification.
Once an extension is enabled, it is only disabled if the WebGL rendering context is lost (see below), with the exception of the "WEBGL_lose_context" extension which remains active through any loss of context. Any objects referenced by a disabled extension, such as the object returned by getExtension, are no longer associated with the WebGL rendering context. Any extension objects that derive from WebGLObject have their invalidated flag set to true. Behavior of extensions' methods after context loss is defined by the steps in the section "The WebGL context".
There are no other mechanisms to disable an extension.
Multiple calls to getExtension with the same extension string, taking into account case-insensitive comparison, must return the same object as long as the extension is enabled. An attempt to use any features of an extension without first calling getExtension to enable it must generate an appropriate GL error and must not make use of the feature.
This specification does not define any extensions. A separate WebGL extension registry defines extensions that may be supported by a particular WebGL implementation.
Returns a list of all the supported extension strings.
Returns an object if, and only if, name is an ASCII case-insensitive match [HTML] for one of the names returned from getSupportedExtensions; otherwise, returns null. The object returned from getExtension contains any constants or functions provided by the extension. A returned object may have no constants or functions if the extension does not define any, but a unique object must still be returned. That object is used to indicate that the extension has been enabled.
WebGL generates a WebGLContextEvent event in response to important changes in status of a WebGL rendering context. Events are sent using the DOM Event System [DOM3EVENTS], and are dispatched to the HTMLCanvasElement or OffscreenCanvas associated with the WebGL rendering context. The types of status changes that can trigger a WebGLContextEvent event are the loss of the context, the restoration of the context, and the inability to create a context.
To fire a WebGL context event named e means that an event using the WebGLContextEvent interface, with its type attribute [DOM4] initialized to e, its cancelable attribute initialized to true, and its isTrusted attribute [DOM4] initialized to true, is to be dispatched at the given object.
// EventInit is defined in the DOM4 specification.
The task source for all tasks queued [HTML] in this section is the WebGL task source.
A string containing additional information, or the empty string if no additional information is available.
Let canvas be the context's canvas.
If context's webgl context lost flag is set, abort these steps.
Set context's webgl context lost flag.
Set the invalidated flag of each WebGLObject instance created by this context.
Disable all extensions except "WEBGL_lose_context".
Fire a WebGL context event named "webglcontextlost" at canvas, with its statusMessage attribute set to "".
If the event's canceled flag is not set, abort these steps.
Perform the following steps asynchronously.
Await a restorable drawing buffer.
Queue a task to restore the drawing buffer for context.
Let canvas be the canvas object associated with context.
If context's webgl context lost flag is not set, abort these steps.
Create a drawing buffer using the settings specified in context's context creation parameters, and associate the drawing buffer with context, discarding any previous drawing buffer.
Clear context's webgl context lost flag.
Reset context's OpenGL error state.
Fire a WebGL context event named "webglcontextrestored" at canvas, with its statusMessage attribute set to "".
Once the context is restored, WebGL resources such as textures and buffers that were created before the context was lost are no longer valid. The application needs to reinitialize the context's state and recreate all such resources.
Fire a WebGL context event named "webglcontextcreationerror" at canvas, optionally with its statusMessage attribute set to a platform dependent string about the nature of the failure.
This section describes changes made to the WebGL API relative to the OpenGL ES 2.0 API to improve portability across various operating systems and devices.
In the WebGL API, a given buffer object may only be bound to one of the ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER binding points in its lifetime. This restriction implies that a given buffer object may contain either vertices or indices, but not both.
The type of a WebGLBuffer is initialized the first time it is passed as an argument to bindBuffer. A subsequent call to bindBuffer which attempts to bind the same WebGLBuffer to the other binding point will generate an INVALID_OPERATION error, and the state of the binding point will remain untouched.
The WebGL API does not support client-side arrays.
If a vertex attribute is enabled as an array via enableVertexAttribArray but no buffer is bound to that attribute (generally via bindBuffer and vertexAttribPointer), then draw commands (drawArrays or drawElements) will generate an INVALID_OPERATION error.
If an indexed draw command (drawElements) is called and no WebGLBuffer is bound to the ELEMENT_ARRAY_BUFFER binding point, an INVALID_OPERATION error is generated.
If vertexAttribPointer is called without a WebGLBuffer bound to the ARRAY_BUFFER binding point, and offset is non-zero, an INVALID_OPERATION error is generated.
Allowing setting VERTEX_ATTRIB_ARRAY_BUFFER_BINDING to null even though client-side arrays are never supported allows for clearing the binding to its original state, which isn't strictly possible otherwise.
This also matches the behavior in OpenGL ES 3.0.5 [GLES30] p25 for non-default VAO objects.
The WebGL API does not support default textures. A non-null WebGLTexture object must be bound in order for texture-related operations and queries to succeed.
Accessing binary representations of compiled shaders is not supported in the WebGL API. This includes the OpenGL ES 2.0 ShaderBinary entry point. In addition, querying shader binary formats and the availability of a shader compiler via getParameter is not supported in the WebGL API.
All WebGL implementations must implicitly support an on-line shader compiler.
The offset arguments to drawElements and vertexAttribPointer, and the stride argument to vertexAttribPointer, must be a multiple of the size of the data type passed to the call, or an INVALID_OPERATION error is generated.
"Clients must align data elements consistent with the requirements of the client platform, with an additional base-level requirement that an offset within a buffer to a datum comprising N basic machine units be a multiple of N."
In addition the offset argument to drawElements must be non-negative or an INVALID_VALUE error is generated.
The WebGL implementation may generate an INVALID_OPERATION error and draw no geometry.
Values from anywhere within the buffer object.
If a vertex attribute is enabled as an array, a buffer is bound to that attribute, but the attribute is not consumed by the current program, then regardless of the size of the bound buffer, it will not cause any error to be generated during a call to drawArrays or drawElements.
Calling an indexed drawing command (drawElements) that fetches index elements outside the bounds of ELEMENT_ARRAY_BUFFER will result in an INVALID_OPERATION error.
WebGL adds the DEPTH_STENCIL_ATTACHMENT framebuffer object attachment point and the DEPTH_STENCIL renderbuffer internal format. To attach both depth and stencil buffers to a framebuffer object, call renderbufferStorage with the DEPTH_STENCIL internal format, and then call framebufferRenderbuffer with the DEPTH_STENCIL_ATTACHMENT attachment point.
A renderbuffer attached to the DEPTH_ATTACHMENT attachment point must be allocated with the DEPTH_COMPONENT16 internal format. A renderbuffer attached to the STENCIL_ATTACHMENT attachment point must be allocated with the STENCIL_INDEX8 internal format. A renderbuffer attached to the DEPTH_STENCIL_ATTACHMENT attachment point must be allocated with the DEPTH_STENCIL internal format.
The following calls, which either modify or read the framebuffer, must generate an INVALID_FRAMEBUFFER_OPERATION error and return early, leaving the contents of the framebuffer, destination texture or destination memory untouched.
The width and height of the texture are set to the current values of the width and height properties of the ImageData object, representing the actual pixel width and height of the ImageData object.
If a bitmap is uploaded, the width and height of the texture are set to the width and height of the uploaded bitmap in pixels. If an SVG image is uploaded, the width and height of the texture are set to the current values of the width and height properties of the HTMLImageElement object.
The width and height of the texture are set to the current values of the width and height properties of the HTMLCanvasElement or OffscreenCanvas object.
The width and height of the texture are set to the width and height of the uploaded frame of the video in pixels.
The WebGL API supports the following additional parameters to pixelStorei.
If set, then during any subsequent calls to texImage2D or texSubImage2D, the source data is flipped along the vertical axis, so that conceptually the last row is the first one transferred. The initial value is false. Any non-zero value is interpreted as true.
If set, then during any subsequent calls to texImage2D or texSubImage2D, the alpha channel of the source data, if present, is multiplied into the color channels during the data transfer. The initial value is false. Any non-zero value is interpreted as true.
If set to BROWSER_DEFAULT_WEBGL, then the browser's default colorspace conversion is applied during subsequent texImage2D and texSubImage2D calls taking HTMLImageElement. The precise conversions may be specific to both the browser and file type. If set to NONE, no colorspace conversion is applied. The initial value is BROWSER_DEFAULT_WEBGL.
If the TexImageSource is an ImageBitmap, then these three parameters will be ignored. Instead the equivalent ImageBitmapOptions should be used to create an ImageBitmap with the desired format.
In the WebGL API, three functions read the framebuffer: copyTexImage2D, copyTexSubImage2D, and readPixels. copyTexImage2D is defined to generate the RGBA value (0, 0, 0, 0) for any pixel outside of the bound framebuffer. copyTexSubImage2D and readPixels are defined not to touch the corresponding destination range for any pixel outside the bound framebuffer.
In the WebGL API, if stencil testing is enabled and the currently bound framebuffer has a stencil buffer, then it is illegal to draw while any of the following cases are true. Doing so will generate an INVALID_OPERATION error.
The WebGL API supports vertex attribute data strides up to 255 bytes. A call to vertexAttribPointer will generate an INVALID_VALUE error if the value for the stride parameter exceeds 255.
The WebGL API does not support depth ranges with where the near plane is mapped to a value greater than that of the far plane. A call to depthRange will generate an INVALID_OPERATION error if zNear is greater than zFar.
In the WebGL API, constant color and constant alpha cannot be used together as source and destination factors in the blend function. A call to blendFunc will generate an INVALID_OPERATION error if one of the two factors is set to CONSTANT_COLOR or ONE_MINUS_CONSTANT_COLOR and the other to CONSTANT_ALPHA or ONE_MINUS_CONSTANT_ALPHA. A call to blendFuncSeparate will generate an INVALID_OPERATION error if srcRGB is set to CONSTANT_COLOR or ONE_MINUS_CONSTANT_COLOR and dstRGB is set to CONSTANT_ALPHA or ONE_MINUS_CONSTANT_ALPHA or vice versa.
The WebGL API does not support the GL_FIXED data type.
Per Supported GLSL Constructs, identifiers starting with "webgl_" and "_webgl_" are reserved for use by WebGL.
In the OpenGL ES 2.0 API, the available extensions are determined by calling glGetString(GL_EXTENSIONS), which returns a space-separated list of extension strings. In the WebGL API, the EXTENSIONS enumerant has been removed. Instead, getSupportedExtensions must be called to determine the set of available extensions.
The compressedTexImage2D and compressedTexSubImage2D methods generate an INVALID_ENUM error.
Calling getParameter with the argument COMPRESSED_TEXTURE_FORMATS returns a zero-length array (of type Uint32Array).
The GLSL ES spec [GLES20GLSL] does not define a limit to the length of tokens. WebGL requires support of tokens up to 256 characters in length. Shaders containing tokens longer than 256 characters must fail to compile.
The GLSL ES spec [GLES20GLSL] defines the source character set for the OpenGL ES shading language to be ISO/IEC 646:1991, commonly called ASCII [ASCII]. If a string containing a character not in this set is passed to any of the shader-related entry points bindAttribLocation, getAttribLocation, getUniformLocation, or shaderSource, an INVALID_VALUE error will be generated. The exception is that any character allowed in an HTML DOMString [DOMSTRING] may be used in GLSL comments. Such use must not generate an error.
Some GLSL implementations disallow characters outside the ASCII range, even in comments. The WebGL implementation needs to prevent errors in such cases. The recommended technique is to preprocess the GLSL string, removing all comments, but maintaining the line numbering for debugging purposes by inserting newline characters as needed.
WebGL imposes a limit on the nesting of structures in GLSL shaders. Nesting occurs when a field in a struct refers to another struct type; the GLSL ES spec [GLES20GLSL] forbids embedded structure definitions. The fields in a top-level struct definition have a nesting level of 1.
WebGL requires support of a structure nesting level of 4. Shaders containing structures nested more than 4 levels deep must fail to compile.
WebGL imposes a limit of 256 characters on the lengths of uniform and attribute locations.
In the WebGL API, the enumerants INFO_LOG_LENGTH, SHADER_SOURCE_LENGTH, ACTIVE_UNIFORM_MAX_LENGTH, and ACTIVE_ATTRIBUTE_MAX_LENGTH have been removed. In the OpenGL ES 2.0 API, these enumerants are needed to determine the size of buffers passed to calls like glGetActiveAttrib. In the WebGL API, the analogous calls (getActiveAttrib, getActiveUniform, getProgramInfoLog, getShaderInfoLog, and getShaderSource) all return DOMString.
In the WebGL API, the type argument passed to texSubImage2D must match the type used to originally define the texture object (i.e., using texImage2D).
The OpenGL ES Shading Language, Version 1.00 [GLES20GLSL], Appendix A, Section 7 "Counting of Varyings and Uniforms" defines a conservative algorithm for computing the storage required for all of the uniform and varying variables in a shader. The GLSL ES specification requires that if the packing algorithm defined in Appendix A succeeds, then the shader must succeed compilation on the target platform. The WebGL API further requires that if the packing algorithm fails either for the uniform variables of a shader or for the varying variables of a program, compilation or linking must fail.
The text above defines the circumstances under which compilation or linking of a shader or program must fail due to the constraints enforced by the packing algorithm. It is not guaranteed that a shader which uses more variables than the minimum required amount whose variables pack successfully according to this algorithm will compile successfully. Inefficiencies have been observed in implementations, including expansion of scalar arrays to consume multiple columns. Developers should avoid relying heavily upon automatic packing of multiple variables into columns. Instead, define larger variables (like vec4) and explicitly pack values into the rightmost columns.
In the OpenGL ES 2.0 API, it's possible to make calls that both write to and read from the same texture, creating a feedback loop. It specifies that where these feedback loops exist, undefined behavior results.
In the WebGL API, such operations that would cause such feedback loops (by the definitions in the OpenGL ES 2.0 spec) will instead generate an INVALID_OPERATION error.
In the OpenGL ES 2.0 API, it is not specified what happens when a command tries to source data from a missing attachment, such as ReadPixels of color data from a complete framebuffer that does not have a color attachment.
In the OpenGL ES 2.0 API, it is not specified what happens when a command tries to draw to a missing attachment, such as clearing a draw buffer from a complete framebuffer that does not have a color attachment.
In the WebGL API, if the width parameter passed to lineWidth is set to NaN, an INVALID_VALUE error is generated and the line width is not changed.
It is possible for an application to bind more than one attribute name to the same location. This is referred to as aliasing. When more than one attributes that are aliased to the same location are active in the executable program, linkProgram should fail.
The GLSL ES [GLES20GLSL] spec leaves the value of gl_Position as undefined unless it is written to in a vertex shader. WebGL guarantees that gl_Position's initial value is (0,0,0,0).
Compilers should generate a warning when a global variable initializer is in violation of the unmodified GLSL ES spec i.e. when a global variable initializer is not a constant expression.
This behavior has existed in WebGL implementations for several years. Fixing this behavior to be consistent with the GLSL ES specification would have a large compatibility impact with existing content.
The C++ standard, which the GLSL ES preprocessor specification refers to, has undefined behavior when the defined operator is generated by macro replacement when parsing the controlling expression of an #if or #elif directive. When shader code processed by the WebGL API generates the token defined during macro replacement inside a preprocessor expression, that must result in a compiler error.
This has no effect on macro expansion outside preprocessor directives that handle the defined operator.
Using defined as a macro name also has undefined behavior in the C++ standard. In the WebGL API, using defined as a macro name must result in a compiler error.
Behavior of the WebGL API should be consistent in cases where the native API spec allows undefined behavior.
The GLSL ES 1.00 [GLES20GLSL] specification mandates that #extension directives must occur before any non-preprocessor tokens unless the extension specification says otherwise. In the WebGL API, #extension directives may always occur after non-preprocessor tokens in GLSL ES 1.00 shaders. The scope of #extension directives in GLSL ES 1.00 shaders is always the whole shader, and #extension directives that occur later override those seen earlier for the whole shader.
Letting extensions determine where the #extension directives should be placed has resulted in a lot of room for interpretation in the spec. In practice GLES implementations have not enforced the rule that's written in the GLSL ES spec, and neither have WebGL implementations, so relaxing the rule is the only way to make the spec well-defined while being compatible with existing content.
In the WebGL API, a face of a cube map that is not cube complete is not framebuffer attachment complete. Querying framebuffer status when a face of an incomplete cube map is attached must return FRAMEBUFFER_INCOMPLETE_ATTACHMENT.
APIs that WebGL is implemented on, including recent OpenGL core versions and OpenGL ES 3.0 and newer, have a requirement that cube map faces used as a framebuffer attachment must be part of a cube complete cube map. See for example OpenGL ES 3.0.4 §4.4.4 "Framebuffer Completeness", subsection "Framebuffer Attachment Completeness".
Any command that transfers vertices to the GL generates INVALID_OPERATION if the CURRENT_PROGRAM is null. This includes drawElements and drawArrays.
If a fragment shader writes to neither gl_FragColor nor gl_FragData, the values of the fragment colors following shader execution are untouched.
The GLSL ES [GLES20GLSL] spec leaves the value of local and global variables as undefined unless they are initialized by the shader. WebGL guarantees that such variables are initialized to zero: 0.0, vec4(0.0), 0, false, etc.
Some APIs on which WebGL 1.0 is built on use the second rule, and since this conversion is done in fixed-function hardware, it is not possible to emulate one behavior or the other. This difference in behavior does not affect most applications, so a query to determine which behavior is being used has not been added to the WebGL rendering context.
If any of the shaders attached to a WebGL program declare a uniform that has the same name as a statically used vertex attribute, program linking should fail.
This behavior differs from one specified in GLSL ES 3.00.6 section 12.47.
WebGL implementations have enforced this behavior for several years now, due to that some OpenGL drivers don't accept uniforms and vertex attributes with the same name.
HTML5: The Canvas Element , World Wide Web Consortium (W3C).
HTML Living Standard - The OffscreenCanvas interface , WHATWG.
Canvas Context Registry , WHATWG.
ECMAScript® 2015 Language Specification , Ecma International, 2015.
OpenGL® ES Common Profile Specification Version 2.0.25 , A. Munshi, J. Leech, November 2010.
The OpenGL® ES Shading Language Version 1.00 , R. Simpson, May 2009.
Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification , B. Bos, T. Celik, I. Hickson, H. W. Lie, June 2011.
Cross-Origin Resource Sharing , A. van Kesteren, July 2010.
DOM4 , A. van Kesteren, A. Gregor, Ms2ger.
Document Object Model (DOM) Level 3 Events Specification , Doug Schepers and Jacob Rossi. W3C.
HTML , I. Hickson, June 2011.
Web IDL: W3C Editor’s Draft , C. McCormack, B. Zbarsky, T. Langel.
Document Object Model Core: The DOMString type , World Wide Web Consortium (W3C).
KHR_robust_buffer_access_behavior OpenGL ES extension , Leech, J. and Daniell, P., August, 2014.
(Non-normative) Multiple buffering . Wikipedia.
This specification is produced by the Khronos WebGL Working Group.
Additional thanks to: Alan Hudson (Yumetech), Benoit Jacob (Mozilla), Bill Licea Kane (AMD), Boris Zbarsky (Mozilla), Cameron McCormack (Mozilla), Cedric Vivier (Zegami), Dan Gessel (Apple), David Ligon (Qualcomm), David Sheets (Ashima Arts), Glenn Maynard, Greg Roth (Nvidia), Jacob Strom (Ericsson), Jeff Gilbert (Mozilla), Kari Pulli (Nokia), Teddie Stenvi (ST-Ericsson), Neil Trevett (Nvidia), Per Wennersten (Ericsson), Per-Erik Brodin (Ericsson), Shiki Okasaka (Google), Tom Olson (ARM), Zhengrong Yao (Ericsson), and the members of the Khronos WebGL Working Group.

References: §2
 §2
 §2
 §4
 §4
 §4
 §2
 §2
 §2
 §4
 §4
 §4
 §2
 §2
 §2
 §3
 §3
 §3
 §4