Simple WebGL Application
Based on the template of previous section, let's add the JavaScript codes to do the WebGL stuff.
<script type="text/javascript">
var gl;
function init() {
if (!window.WebGLRenderingContext) {
alert("Your browser doese not support WebGL!");
return;
}
var canvas = document.getElementById("webgl-canvas");
gl = canvas.getContext("webgl");
if (!gl) {
alert("Unable to initialize WebGL!");
return;
}
gl.clearColor(0.0, 0.0, 0.0, 1.0);
render();
}
function render() {
gl.clear(gl.COLOR_BUFFER_BIT);
}
window.addEventListener("DOMContentLoaded", init);
</script>
View demo.
Key Notes
- WebGL initialization
WebGL Methods
Canvas
getContext
Brief
init and return a WebGL context.
Synopsis
WebGLRenderingContext getContext(type, attributes)
Parameters
- type
-
- "webgl"
- create and return a WebGL context.
- "experimental-webgl"
- create and return an experimental WebGL context.
- attributes
-
- alpha
- boolean. need an alpha buffer?
Default: true - depth
- boolean. need an depth buffer of at least 16 bits?
Default: true - stencil
- boolean. need an stencil buffer of at least 8 bits?
Default: false - antialias
- boolean. need antialias?
Default: true - premultipliedAlpha
- boolean. contains colors with premultiplied alpha?
Default: true - preserveDrawingBuffer
- boolean. preserve drawingBuffer?
Default: false - powerPreference
- string. options: "default", "high-performance", "low-power".
Default: "default" - failIfMajorPerformanceCaveat
- boolean.
Default: false - desynchronized
- boolean.
Default: false
Return
WebGLRenderingContext
WebGLRenderingContext
clear
Brief
clear buffers to preset values.
Synopsis
void clear(GLbitfield mask)
Parameters
- mask
- which buffers to be cleared. Values are:
- GL_COLOR_BUFFER_BIT
- color buffer
- GL_DEPTH_BUFFER_BIT
- depth buffer
- GL_STENCIL_BUFFER_BIT
- stencil buffer
clearColor
Brief
specify clear values for the color buffers.
Synopsis
void clearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
Parameters
- red, green, blue, alpha
- Specify the red, green, blue, alpha values used to clear color buffers. The initial values are all 0.