WebGL
with Three.js
Hola, Montevideo!
What we’ll cover
Introduction
https://www.chromeexperiments.com/globe
Introduction
I hope you’ve got
Sooo - what’s WebGL anyway?
<canvas></canvas>
<script>
var canvas = document.querySelector(“canvas”),
ctx = canvas.getContext(“2d”);
// do 2D operations on the canvas
</script>
Sooo - what’s WebGL anyway?
<canvas></canvas>
<script>
var canvas = document.querySelector(“canvas”),
ctx = canvas.getContext(“2d”);
// do 2D operations on the canvas
</script>
Sooo - what’s WebGL anyway?
<canvas></canvas>
<script>
var canvas = document.querySelector(“canvas”),
ctx = canvas.getContext(“webgl”);
// do 3D operations on the canvas
</script>
Sooo - what’s WebGL anyway?
<canvas></canvas>
<script>
var canvas = document.querySelector(“canvas”),
ctx = canvas.getContext(“webgl”)
|| canvas.getContext(“experimental-webgl”);
// do 3D operations on the canvas
</script>
WebGL =
WebGL 2 = OpenGL ES 3.0 / GLSL 3.3+
Getting started
Coordinate system
Vertices, Faces & shading
Vertices are points in 3D space
Vertices, Faces & shading
Faces connect vertices to areas
Vertices, Faces & shading
Shading determines how things are drawn
Shaders
The pipeline
Aha, so how do I use that?
Very “wordy” API… let’s use something slightly more high level
Why?
gl.clearColor(0.0, 0.0, 0.0, 1.0); �gl.enable(gl.DEPTH_TEST); �gl.depthFunc(gl.LEQUAL); �
Why? (cont)
var triangleVertexPositionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
var vertices = [� 0.0, 1.0, 0.0,� -1.0, -1.0, 0.0,� 1.0, -1.0, 0.0� ];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
triangleVertexPositionBuffer.itemSize = 3;�triangleVertexPositionBuffer.numItems = 3;
Why? (cont)
function render() {
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
gl.drawArrays(gl.TRIANGLES, 0, triangleVertexPositionBuffer.numItems);
}
// and I left out some stuff (matrices for perspective rendering)
How about Three.js?
var camera = new THREE.PerspectiveCamera(45, width/height, 1, 2000);
var scene = new THREE.Scene();
var light = new THREE.AmbientLight();
var renderer = new THREE.WebGLRenderer();
// some more configuration
How about Three.js?
var camera = new THREE.PerspectiveCamera(45, width/height, 1, 2000);
var scene = new THREE.Scene();
var light = new THREE.AmbientLight();
var renderer = new THREE.WebGLRenderer();
// some more configuration
Conveniently wrapped in three-world
Off we go!
Advanced Three.js
http://avgp.github.io/h2g2three/
Lesson 4-6
Three.js performance
Done! / Thank you!