WebGL is a JavaScript port of the
OpenGL ES 2.0 graphics library which makes it possible for web pages to compute a graphic on a device's
GPU and render the result in a
<canvas>
HTML element.
Shader
There are two types of shaders:
- Vertex shaders: They define vertices on the screen by assigning a 4-element vector to
gl_position
.
- Fragment shaders: they run once for each pixel on the scene and determine their color values by assigning a 4-element vector to
gl_FragColor
.
In
JavaScript, a shader is created with
shader = gl.createShader()
.
The source code for a shader is indicated with gl.shaderSource(shader, source_code)
.
Then the shader is compiled with gl.compileShader(shader))
.
Finally, the shaders are added to the gl-program with gl.attachShaders(gl_program, shader)
.
Determining if WebGL is supported
If a
browser supports WebGL can be determined by checking for the existance of
window.WebGLRenderingContext
with
JavaScript.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Does the browser support webgl?</title>
<script type="application/x-javascript">
function main() {
var result = document.getElementById('result');
if (window.WebGLRenderingContext) {
result.innerHTML = "Browser supports WebGl";
}
else {
result.innerHTML = "Browser does not suppoert WebGl";
}
}
window.onload = main;
</script>
</head>
<body onload='main()'>
<div id='result'></div>
</body>
</html>