WebGL is a JavaScript API for rendering interactive 3D graphics within any compatible web browser without the use of plug-ins. It can be used for data visualization, creative coding, 3D modeling, games, and more. WebGL works by using JavaScript to interface with the GPU through WebGL APIs to run GLSL shaders that render 3D scenes. To get started, one needs to choose a WebGL library like Three.js, add a <canvas> element, and get the WebGL context. Sample code is provided to render a 3D model by loading geometry, adding lights and materials, and animating the scene render.
7. <canvas id=‘c’ width=‘100’ height=‘100’></canvas>
document.getElementById(‘c’).getContext(‘webgl’) **
** in some browsers the context’s ‘experimental-webgl’, be sure to include both
9. - data visualization
- creative coding
- art
- 3D design environments
- music videos
- plotting mathematical functions and models
- modeling 3D objects and space
- creating textures
- physical simulations
- efficient processing of any kind of large data
- ...
38. onError: function() {
alert("There was an error creating the app.");
},
onLoad: function(app) {
//Unpack app properties
var gl = app.gl,
program = app.program,
scene = app.scene,
canvas = app.canvas,
camera = app.camera;
//get light config from forms
lighting = $('lighting'),
ambient = {
r: $('ambientR'),
g: $('ambientG'),
b: $('ambientB')
},
direction = {
x: $('lightDirectionX'),
y: $('lightDirectionY'),
z: $('lightDirectionZ'),
r: $('directionalR'),
g: $('directionalG'),
b: $('directionalB')
};
//Basic gl setup
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clearDepth(1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.viewport(0, 0, canvas.width, canvas.height);
39. //Add object to the scene
scene.add(moon);
//Draw the scene
draw();
function draw() {
//clear the screen
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
//Setup lighting
var lights = scene.config.lights;
lights.enable = lighting.checked;
lights.ambient = {
r: +ambient.r.value,
g: +ambient.g.value,
b: +ambient.b.value
};
lights.directional = {
color: {
r: +direction.r.value,
g: +direction.g.value,
b: +direction.b.value
},
direction: {
x: +direction.x.value,
y: +direction.y.value,
z: +direction.z.value
}
};
//render moon
scene.render();
//Animate
Fx.requestAnimationFrame(draw);
}
}
});
}
40. Some more resources
- An Introduction to WebGL @ dev.Opera
- PhiloGL
- PhiloGL tutorial
- WebGL w/o a library @ dev.Opera
- Porting 3D models to WebGL @ dev.Opera
- News and resources @ the Learning WebGL blog
- WebGL w/o a library @ Learning WebGL
- Three.js
- Three.js tutorial
- WebGL FAQ
- The Khronos WebGL forum