SlideShare a Scribd company logo
1 of 21
Download to read offline
WebGL with THREE.js


Wednesday, December 12, 12
@antonnarusberg
                                 anton@cannedapps.com


                             Google Developers Group Tallinn
                                  http://bit.ly/gdgtallinn
                                     @GDGTallinn



Wednesday, December 12, 12
3D in Web Browsers




Wednesday, December 12, 12
3D in Web Browsers

   Full power of computer's GPU using only JS, web browser
              and standard web technology stack.


                             Old way - plugins, native applications

                                     New way - WebGL




Wednesday, December 12, 12
Browser compatibility




Wednesday, December 12, 12
So how do you use it?

                             WebGL is an API, accessed through
                             JavaScript programming interfaces.


                             Analogous to 2D drawing using the
                                  HTML5 Canvas element


                             Based on OpenGL ES 2.0 standard


Wednesday, December 12, 12
An (overly) simplified Example:
                    Cube with plain WebGL




Wednesday, December 12, 12
// get the WebGL context to access the API
               var canvas = document.getElementById("lesson04-canvas");
               gl = canvas.getContext("experimental-webgl");


               // Set up Shaders
               var fragmentShader = getShader(gl, "shader-fs");
               var vertexShader = getShader(gl, "shader-vs");

               shaderProgram = gl.createProgram();
               gl.attachShader(shaderProgram, vertexShader);
               gl.attachShader(shaderProgram, fragmentShader);
               gl.linkProgram(shaderProgram);

               gl.useProgram(shaderProgram);

               // ....




Wednesday, December 12, 12
<script id="shader-fs" type="x-shader/x-fragment">
                   precision mediump float;

                   varying vec4 vColor;

                   void main(void) {
                       gl_FragColor = vColor;
                   }
               </script>

               <script id="shader-vs" type="x-shader/x-vertex">
                   attribute vec3 aVertexPosition;
                   attribute vec4 aVertexColor;

                   uniform mat4 uMVMatrix;
                   uniform mat4 uPMatrix;

                   varying vec4 vColor;

                   void main(void) {
                       gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
                       vColor = aVertexColor;
                   }
               </script>




Wednesday, December 12, 12
// A taste of creating the array of vertices for the cube
              cubeVertexPositionBuffer = gl.createBuffer();
              gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer);

         vertices = [
              // Front face
              -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0,
              // Back face
              -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0,
              // Top face
              -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0,
              // Bottom face
              -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0,
              // Right face
               1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0,
              // Left face
              -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0
         ];

              gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);




Wednesday, December 12, 12
// Rotating the cube with Matrix computations
             function drawScene() {

                   mat4.translate(mvMatrix, [3.0, 0.0, 0.0]);
                   mat4.rotate(mvMatrix, degToRad(rCube), [1, 1, 1]);

                   gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);

                   // ... Bind buffers etc.

                   gl.drawElements(gl.TRIANGLES, cubeVertexIndexBuffer.numItems,
                   gl.UNSIGNED_SHORT, 0);

                   // ...
             }

             function tick() {
                requestAnimFrame(tick);
                rCube += 1;
                drawScene();
             }




Wednesday, December 12, 12
Skills needed for plain WebGL

       * GLSL, the shading language used by OpenGL and
       WebGL

       * Lots of Math for Matrix computation to set up
       transformations

       * Creating Vertex buffers to hold data about vertex
       positions, normals, colors, and textures


Wednesday, December 12, 12
THREE.js to the rescue!




Wednesday, December 12, 12
THREE.js

       * Abstracts away all the painful overhead

       * Elegant API to create and manipulate Cameras,
       Objects, Lights, Materials etc.

       * THREE.js is Open Source




Wednesday, December 12, 12
A Cube example using THREE.js


       http://learningthreejs.com/data/
       lets_do_a_cube/docs/lets_do_a_cube.html

       Jerome Etienne - great tutorials on THREE.js




Wednesday, December 12, 12
// Set up a Camera
             camera = new THREE.Camera(70, window.innerWidth / window.innerHeight, 1,
             1000);
             camera.position.y = 150;
             camera.position.z = 350;
             camera.target.position.y = 150;

             // Create a Scene
             scene = new THREE.Scene();

             // Create a Cube
             material = new THREE.MeshNormalMaterial();
             cube = new THREE.Mesh( new THREE.CubeGeometry( 200, 200, 200 ), material);
             cube.position.y = 150;


             // Add the Cube to the Scene
             scene.addObject( cube );


             // Boilerplate
             renderer = new THREE.WebGLRenderer();
             renderer.setSize( window.innerWidth, window.innerHeight );
             $(“#container”).appendChild( renderer.domElement );




Wednesday, December 12, 12
function animate() {
             	 render();


                   // Loop
             	     requestAnimationFrame( animate );
             }

             function render() {
                   // Rotate
             	     cube.rotation.x += 0.02;
             	     cube.rotation.y += 0.0225;
             	     cube.rotation.z += 0.0175;


                   // Bounce
                   var dtime	= Date.now() - startTime;
             	     cube.scale.x	 = 1.0 + 0.3*Math.sin(dtime/300);
             	     cube.scale.y	 = 1.0 + 0.3*Math.sin(dtime/300);
             	     cube.scale.z	 = 1.0 + 0.3*Math.sin(dtime/300);

             	     renderer.render( scene, camera );
             }




Wednesday, December 12, 12
It’s alive!




Wednesday, December 12, 12
More Features
       Renderers
       WebGL, <canvas>, <svg>

       Cameras
       Perspective and orthographic; controllers: trackball, FPS, path and more

       Lights
       Ambient, direction, point, spot and hemisphere lights. Cast and receive shadows

       Materials
       Lambert, Phong and more - with textures, smooth-shading

       Shaders
       Access to full WebGL capabilities like lens flare, depth pass and an extensive post-processing library

       Objects
       meshes, particles, sprites, lines, ribbons, ...

       Geometry
       plane, cube, sphere, torus, 3D text and more

       Export/Import
       utilities to create Three.js-compatible JSON files from: Blender, CTM, FBX, 3D Max, and OBJ



Wednesday, December 12, 12
http://threejs.org/

           https://github.com/mrdoob/three.js

                             http://learningthreejs.com


Wednesday, December 12, 12
Thank you!




Wednesday, December 12, 12

More Related Content

What's hot

[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
Unreal python
Unreal pythonUnreal python
Unreal pythonTonyCms
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.jsPagepro
 
ARCHITECTURE MICROSERVICE : TOUR D’HORIZON DU CONCEPT ET BONNES PRATIQUES
ARCHITECTURE MICROSERVICE : TOUR D’HORIZON DU CONCEPT ET BONNES PRATIQUESARCHITECTURE MICROSERVICE : TOUR D’HORIZON DU CONCEPT ET BONNES PRATIQUES
ARCHITECTURE MICROSERVICE : TOUR D’HORIZON DU CONCEPT ET BONNES PRATIQUESSOAT
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS IntroductionDavid Ličen
 
Flutter Festivals GDSC ASEB | Introduction to Dart
Flutter Festivals GDSC ASEB | Introduction to DartFlutter Festivals GDSC ASEB | Introduction to Dart
Flutter Festivals GDSC ASEB | Introduction to DartSadhanaParameswaran
 
AAA게임_UI_최적화_및_빌드하기.pptx
AAA게임_UI_최적화_및_빌드하기.pptxAAA게임_UI_최적화_및_빌드하기.pptx
AAA게임_UI_최적화_및_빌드하기.pptxTonyCms
 
Infra as Code with Packer, Ansible and Terraform
Infra as Code with Packer, Ansible and TerraformInfra as Code with Packer, Ansible and Terraform
Infra as Code with Packer, Ansible and TerraformInho Kang
 
도커 무작정 따라하기: 도커가 처음인 사람도 60분이면 웹 서버를 올릴 수 있습니다!
도커 무작정 따라하기: 도커가 처음인 사람도 60분이면 웹 서버를 올릴 수 있습니다!도커 무작정 따라하기: 도커가 처음인 사람도 60분이면 웹 서버를 올릴 수 있습니다!
도커 무작정 따라하기: 도커가 처음인 사람도 60분이면 웹 서버를 올릴 수 있습니다!pyrasis
 

What's hot (20)

Vue 2 vs Vue 3.pptx
Vue 2 vs Vue 3.pptxVue 2 vs Vue 3.pptx
Vue 2 vs Vue 3.pptx
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
Express js
Express jsExpress js
Express js
 
Unreal python
Unreal pythonUnreal python
Unreal python
 
Vertx
VertxVertx
Vertx
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Vue.js for beginners
Vue.js for beginnersVue.js for beginners
Vue.js for beginners
 
React/Redux
React/ReduxReact/Redux
React/Redux
 
ARCHITECTURE MICROSERVICE : TOUR D’HORIZON DU CONCEPT ET BONNES PRATIQUES
ARCHITECTURE MICROSERVICE : TOUR D’HORIZON DU CONCEPT ET BONNES PRATIQUESARCHITECTURE MICROSERVICE : TOUR D’HORIZON DU CONCEPT ET BONNES PRATIQUES
ARCHITECTURE MICROSERVICE : TOUR D’HORIZON DU CONCEPT ET BONNES PRATIQUES
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
 
Flutter Festivals GDSC ASEB | Introduction to Dart
Flutter Festivals GDSC ASEB | Introduction to DartFlutter Festivals GDSC ASEB | Introduction to Dart
Flutter Festivals GDSC ASEB | Introduction to Dart
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
 
Web AR
Web ARWeb AR
Web AR
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
AAA게임_UI_최적화_및_빌드하기.pptx
AAA게임_UI_최적화_및_빌드하기.pptxAAA게임_UI_최적화_및_빌드하기.pptx
AAA게임_UI_최적화_및_빌드하기.pptx
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
Vue, vue router, vuex
Vue, vue router, vuexVue, vue router, vuex
Vue, vue router, vuex
 
Infra as Code with Packer, Ansible and Terraform
Infra as Code with Packer, Ansible and TerraformInfra as Code with Packer, Ansible and Terraform
Infra as Code with Packer, Ansible and Terraform
 
도커 무작정 따라하기: 도커가 처음인 사람도 60분이면 웹 서버를 올릴 수 있습니다!
도커 무작정 따라하기: 도커가 처음인 사람도 60분이면 웹 서버를 올릴 수 있습니다!도커 무작정 따라하기: 도커가 처음인 사람도 60분이면 웹 서버를 올릴 수 있습니다!
도커 무작정 따라하기: 도커가 처음인 사람도 60분이면 웹 서버를 올릴 수 있습니다!
 

Viewers also liked

Web gl game development
Web gl game developmentWeb gl game development
Web gl game developmentwebglgame
 
cloud conference 2013 - Infrastructure as a Service in Amazon Web Services
cloud conference 2013 - Infrastructure as a Service in Amazon Web Servicescloud conference 2013 - Infrastructure as a Service in Amazon Web Services
cloud conference 2013 - Infrastructure as a Service in Amazon Web ServicesVMEngine
 
Getting Started with WebGL
Getting Started with WebGLGetting Started with WebGL
Getting Started with WebGLChihoon Byun
 
From Hello World to the Interactive Web with Three.js: Workshop at FutureJS 2014
From Hello World to the Interactive Web with Three.js: Workshop at FutureJS 2014From Hello World to the Interactive Web with Three.js: Workshop at FutureJS 2014
From Hello World to the Interactive Web with Three.js: Workshop at FutureJS 2014Verold
 
Starting Development for Nokia N9
Starting Development for Nokia N9Starting Development for Nokia N9
Starting Development for Nokia N9tpyssysa
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design PatternsYnon Perek
 
Open stack implementation
Open stack implementation Open stack implementation
Open stack implementation Soumyajit Basu
 
Qt State Machine Framework
Qt State Machine FrameworkQt State Machine Framework
Qt State Machine Frameworkaccount inactive
 
Cutest technology of them all - Forum Nokia Qt Webinar December 2009
Cutest technology of them all - Forum Nokia Qt Webinar December 2009Cutest technology of them all - Forum Nokia Qt Webinar December 2009
Cutest technology of them all - Forum Nokia Qt Webinar December 2009Nokia
 
Open Stack vs .NET Stack - For Startups
Open Stack vs .NET Stack - For StartupsOpen Stack vs .NET Stack - For Startups
Open Stack vs .NET Stack - For StartupsBryan Starbuck
 
Introduction to WebGL and Three.js
Introduction to WebGL and Three.jsIntroduction to WebGL and Three.js
Introduction to WebGL and Three.jsJames Williams
 
Module 4: NETCONF Tutorial
Module 4: NETCONF Tutorial Module 4: NETCONF Tutorial
Module 4: NETCONF Tutorial Tail-f Systems
 
Amazon Web Service EC2 & S3
Amazon Web Service EC2 & S3Amazon Web Service EC2 & S3
Amazon Web Service EC2 & S3Pravin Vaja
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIICS
 
Best Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIBest Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIICS
 

Viewers also liked (20)

Web gl game development
Web gl game developmentWeb gl game development
Web gl game development
 
cloud conference 2013 - Infrastructure as a Service in Amazon Web Services
cloud conference 2013 - Infrastructure as a Service in Amazon Web Servicescloud conference 2013 - Infrastructure as a Service in Amazon Web Services
cloud conference 2013 - Infrastructure as a Service in Amazon Web Services
 
Getting Started with WebGL
Getting Started with WebGLGetting Started with WebGL
Getting Started with WebGL
 
Web Sockets in Java EE 7
Web Sockets in Java EE 7Web Sockets in Java EE 7
Web Sockets in Java EE 7
 
From Hello World to the Interactive Web with Three.js: Workshop at FutureJS 2014
From Hello World to the Interactive Web with Three.js: Workshop at FutureJS 2014From Hello World to the Interactive Web with Three.js: Workshop at FutureJS 2014
From Hello World to the Interactive Web with Three.js: Workshop at FutureJS 2014
 
Starting Development for Nokia N9
Starting Development for Nokia N9Starting Development for Nokia N9
Starting Development for Nokia N9
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design Patterns
 
Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
 
Open stack implementation
Open stack implementation Open stack implementation
Open stack implementation
 
Qt State Machine Framework
Qt State Machine FrameworkQt State Machine Framework
Qt State Machine Framework
 
Cutest technology of them all - Forum Nokia Qt Webinar December 2009
Cutest technology of them all - Forum Nokia Qt Webinar December 2009Cutest technology of them all - Forum Nokia Qt Webinar December 2009
Cutest technology of them all - Forum Nokia Qt Webinar December 2009
 
Open Stack vs .NET Stack - For Startups
Open Stack vs .NET Stack - For StartupsOpen Stack vs .NET Stack - For Startups
Open Stack vs .NET Stack - For Startups
 
Qt 5 - C++ and Widgets
Qt 5 - C++ and WidgetsQt 5 - C++ and Widgets
Qt 5 - C++ and Widgets
 
Open gl
Open glOpen gl
Open gl
 
Introduction to WebGL and Three.js
Introduction to WebGL and Three.jsIntroduction to WebGL and Three.js
Introduction to WebGL and Three.js
 
Introduction to Qt
Introduction to QtIntroduction to Qt
Introduction to Qt
 
Module 4: NETCONF Tutorial
Module 4: NETCONF Tutorial Module 4: NETCONF Tutorial
Module 4: NETCONF Tutorial
 
Amazon Web Service EC2 & S3
Amazon Web Service EC2 & S3Amazon Web Service EC2 & S3
Amazon Web Service EC2 & S3
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part II
 
Best Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIBest Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part III
 

Similar to WebGL and three.js

Webgl para JavaScripters
Webgl para JavaScriptersWebgl para JavaScripters
Webgl para JavaScriptersgerbille
 
WT-4064, Build Rich Applications with HTML5 and WebGL, by Tony Parisi
WT-4064, Build Rich Applications with HTML5 and WebGL, by Tony ParisiWT-4064, Build Rich Applications with HTML5 and WebGL, by Tony Parisi
WT-4064, Build Rich Applications with HTML5 and WebGL, by Tony ParisiAMD Developer Central
 
3D Web Programming [Thanh Loc Vo , CTO Epsilon Mobile ]
3D Web Programming [Thanh Loc Vo , CTO Epsilon Mobile ]3D Web Programming [Thanh Loc Vo , CTO Epsilon Mobile ]
3D Web Programming [Thanh Loc Vo , CTO Epsilon Mobile ]JavaScript Meetup HCMC
 
WebGL Crash Course
WebGL Crash CourseWebGL Crash Course
WebGL Crash CourseTony Parisi
 
WebGL, HTML5 and How the Mobile Web Was Won
WebGL, HTML5 and How the Mobile Web Was WonWebGL, HTML5 and How the Mobile Web Was Won
WebGL, HTML5 and How the Mobile Web Was WonTony Parisi
 
Deep dive into deeplearn.js
Deep dive into deeplearn.jsDeep dive into deeplearn.js
Deep dive into deeplearn.jsKai Sasaki
 
Leaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGLLeaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGLgerbille
 
Developing Web Graphics with WebGL
Developing Web Graphics with WebGLDeveloping Web Graphics with WebGL
Developing Web Graphics with WebGLTony Parisi
 
WebGL - It's GO Time
WebGL - It's GO TimeWebGL - It's GO Time
WebGL - It's GO TimeTony Parisi
 
Drawing in HTML5 Open House
Drawing in HTML5 Open HouseDrawing in HTML5 Open House
Drawing in HTML5 Open HouseNoam Kfir
 
Rendering of Complex 3D Treemaps (GRAPP 2013)
Rendering of Complex 3D Treemaps (GRAPP 2013)Rendering of Complex 3D Treemaps (GRAPP 2013)
Rendering of Complex 3D Treemaps (GRAPP 2013)Matthias Trapp
 
Leaving Flatland: Getting Started with WebGL- SXSW 2012
Leaving Flatland: Getting Started with WebGL- SXSW 2012Leaving Flatland: Getting Started with WebGL- SXSW 2012
Leaving Flatland: Getting Started with WebGL- SXSW 2012philogb
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
Unconventional webapps with gwt:elemental & html5
Unconventional webapps with gwt:elemental & html5Unconventional webapps with gwt:elemental & html5
Unconventional webapps with gwt:elemental & html5firenze-gtug
 
[JS EXPERIENCE 2018] Jogos em JavaScript com WebGL - Juliana Negreiros, Codem...
[JS EXPERIENCE 2018] Jogos em JavaScript com WebGL - Juliana Negreiros, Codem...[JS EXPERIENCE 2018] Jogos em JavaScript com WebGL - Juliana Negreiros, Codem...
[JS EXPERIENCE 2018] Jogos em JavaScript com WebGL - Juliana Negreiros, Codem...iMasters
 
JavaScript para Graficos y Visualizacion de Datos - BogotaJS
JavaScript para Graficos y Visualizacion de Datos - BogotaJSJavaScript para Graficos y Visualizacion de Datos - BogotaJS
JavaScript para Graficos y Visualizacion de Datos - BogotaJSphilogb
 
Kharkivpy#3: Javascript and Python backend
Kharkivpy#3: Javascript and Python backendKharkivpy#3: Javascript and Python backend
Kharkivpy#3: Javascript and Python backendMax Klymyshyn
 
WebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webWebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webpjcozzi
 
JavaScript para Graficos y Visualizacion de Datos
JavaScript para Graficos y Visualizacion de DatosJavaScript para Graficos y Visualizacion de Datos
JavaScript para Graficos y Visualizacion de Datosphilogb
 

Similar to WebGL and three.js (20)

Webgl para JavaScripters
Webgl para JavaScriptersWebgl para JavaScripters
Webgl para JavaScripters
 
WT-4064, Build Rich Applications with HTML5 and WebGL, by Tony Parisi
WT-4064, Build Rich Applications with HTML5 and WebGL, by Tony ParisiWT-4064, Build Rich Applications with HTML5 and WebGL, by Tony Parisi
WT-4064, Build Rich Applications with HTML5 and WebGL, by Tony Parisi
 
3D Web Programming [Thanh Loc Vo , CTO Epsilon Mobile ]
3D Web Programming [Thanh Loc Vo , CTO Epsilon Mobile ]3D Web Programming [Thanh Loc Vo , CTO Epsilon Mobile ]
3D Web Programming [Thanh Loc Vo , CTO Epsilon Mobile ]
 
WebGL Crash Course
WebGL Crash CourseWebGL Crash Course
WebGL Crash Course
 
WebGL, HTML5 and How the Mobile Web Was Won
WebGL, HTML5 and How the Mobile Web Was WonWebGL, HTML5 and How the Mobile Web Was Won
WebGL, HTML5 and How the Mobile Web Was Won
 
Deep dive into deeplearn.js
Deep dive into deeplearn.jsDeep dive into deeplearn.js
Deep dive into deeplearn.js
 
Leaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGLLeaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGL
 
COLLADA & WebGL
COLLADA & WebGLCOLLADA & WebGL
COLLADA & WebGL
 
Developing Web Graphics with WebGL
Developing Web Graphics with WebGLDeveloping Web Graphics with WebGL
Developing Web Graphics with WebGL
 
WebGL - It's GO Time
WebGL - It's GO TimeWebGL - It's GO Time
WebGL - It's GO Time
 
Drawing in HTML5 Open House
Drawing in HTML5 Open HouseDrawing in HTML5 Open House
Drawing in HTML5 Open House
 
Rendering of Complex 3D Treemaps (GRAPP 2013)
Rendering of Complex 3D Treemaps (GRAPP 2013)Rendering of Complex 3D Treemaps (GRAPP 2013)
Rendering of Complex 3D Treemaps (GRAPP 2013)
 
Leaving Flatland: Getting Started with WebGL- SXSW 2012
Leaving Flatland: Getting Started with WebGL- SXSW 2012Leaving Flatland: Getting Started with WebGL- SXSW 2012
Leaving Flatland: Getting Started with WebGL- SXSW 2012
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Unconventional webapps with gwt:elemental & html5
Unconventional webapps with gwt:elemental & html5Unconventional webapps with gwt:elemental & html5
Unconventional webapps with gwt:elemental & html5
 
[JS EXPERIENCE 2018] Jogos em JavaScript com WebGL - Juliana Negreiros, Codem...
[JS EXPERIENCE 2018] Jogos em JavaScript com WebGL - Juliana Negreiros, Codem...[JS EXPERIENCE 2018] Jogos em JavaScript com WebGL - Juliana Negreiros, Codem...
[JS EXPERIENCE 2018] Jogos em JavaScript com WebGL - Juliana Negreiros, Codem...
 
JavaScript para Graficos y Visualizacion de Datos - BogotaJS
JavaScript para Graficos y Visualizacion de Datos - BogotaJSJavaScript para Graficos y Visualizacion de Datos - BogotaJS
JavaScript para Graficos y Visualizacion de Datos - BogotaJS
 
Kharkivpy#3: Javascript and Python backend
Kharkivpy#3: Javascript and Python backendKharkivpy#3: Javascript and Python backend
Kharkivpy#3: Javascript and Python backend
 
WebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webWebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open web
 
JavaScript para Graficos y Visualizacion de Datos
JavaScript para Graficos y Visualizacion de DatosJavaScript para Graficos y Visualizacion de Datos
JavaScript para Graficos y Visualizacion de Datos
 

WebGL and three.js

  • 2. @antonnarusberg anton@cannedapps.com Google Developers Group Tallinn http://bit.ly/gdgtallinn @GDGTallinn Wednesday, December 12, 12
  • 3. 3D in Web Browsers Wednesday, December 12, 12
  • 4. 3D in Web Browsers Full power of computer's GPU using only JS, web browser and standard web technology stack. Old way - plugins, native applications New way - WebGL Wednesday, December 12, 12
  • 6. So how do you use it? WebGL is an API, accessed through JavaScript programming interfaces. Analogous to 2D drawing using the HTML5 Canvas element Based on OpenGL ES 2.0 standard Wednesday, December 12, 12
  • 7. An (overly) simplified Example: Cube with plain WebGL Wednesday, December 12, 12
  • 8. // get the WebGL context to access the API var canvas = document.getElementById("lesson04-canvas"); gl = canvas.getContext("experimental-webgl"); // Set up Shaders var fragmentShader = getShader(gl, "shader-fs"); var vertexShader = getShader(gl, "shader-vs"); shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); gl.useProgram(shaderProgram); // .... Wednesday, December 12, 12
  • 9. <script id="shader-fs" type="x-shader/x-fragment">     precision mediump float;     varying vec4 vColor;     void main(void) {         gl_FragColor = vColor;     } </script> <script id="shader-vs" type="x-shader/x-vertex">     attribute vec3 aVertexPosition;     attribute vec4 aVertexColor;     uniform mat4 uMVMatrix;     uniform mat4 uPMatrix;     varying vec4 vColor;     void main(void) {         gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);         vColor = aVertexColor;     } </script> Wednesday, December 12, 12
  • 10. // A taste of creating the array of vertices for the cube cubeVertexPositionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer); vertices = [             // Front face             -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0,             // Back face             -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0,             // Top face             -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0,             // Bottom face             -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0,             // Right face              1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0,             // Left face             -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0        ]; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); Wednesday, December 12, 12
  • 11. // Rotating the cube with Matrix computations function drawScene() { mat4.translate(mvMatrix, [3.0, 0.0, 0.0]); mat4.rotate(mvMatrix, degToRad(rCube), [1, 1, 1]); gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix); // ... Bind buffers etc. gl.drawElements(gl.TRIANGLES, cubeVertexIndexBuffer.numItems, gl.UNSIGNED_SHORT, 0); // ... } function tick() { requestAnimFrame(tick); rCube += 1; drawScene(); } Wednesday, December 12, 12
  • 12. Skills needed for plain WebGL * GLSL, the shading language used by OpenGL and WebGL * Lots of Math for Matrix computation to set up transformations * Creating Vertex buffers to hold data about vertex positions, normals, colors, and textures Wednesday, December 12, 12
  • 13. THREE.js to the rescue! Wednesday, December 12, 12
  • 14. THREE.js * Abstracts away all the painful overhead * Elegant API to create and manipulate Cameras, Objects, Lights, Materials etc. * THREE.js is Open Source Wednesday, December 12, 12
  • 15. A Cube example using THREE.js http://learningthreejs.com/data/ lets_do_a_cube/docs/lets_do_a_cube.html Jerome Etienne - great tutorials on THREE.js Wednesday, December 12, 12
  • 16. // Set up a Camera camera = new THREE.Camera(70, window.innerWidth / window.innerHeight, 1, 1000); camera.position.y = 150; camera.position.z = 350; camera.target.position.y = 150; // Create a Scene scene = new THREE.Scene(); // Create a Cube material = new THREE.MeshNormalMaterial(); cube = new THREE.Mesh( new THREE.CubeGeometry( 200, 200, 200 ), material); cube.position.y = 150; // Add the Cube to the Scene scene.addObject( cube ); // Boilerplate renderer = new THREE.WebGLRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); $(“#container”).appendChild( renderer.domElement ); Wednesday, December 12, 12
  • 17. function animate() { render(); // Loop requestAnimationFrame( animate ); } function render() { // Rotate cube.rotation.x += 0.02; cube.rotation.y += 0.0225; cube.rotation.z += 0.0175; // Bounce var dtime = Date.now() - startTime; cube.scale.x = 1.0 + 0.3*Math.sin(dtime/300); cube.scale.y = 1.0 + 0.3*Math.sin(dtime/300); cube.scale.z = 1.0 + 0.3*Math.sin(dtime/300); renderer.render( scene, camera ); } Wednesday, December 12, 12
  • 19. More Features Renderers WebGL, <canvas>, <svg> Cameras Perspective and orthographic; controllers: trackball, FPS, path and more Lights Ambient, direction, point, spot and hemisphere lights. Cast and receive shadows Materials Lambert, Phong and more - with textures, smooth-shading Shaders Access to full WebGL capabilities like lens flare, depth pass and an extensive post-processing library Objects meshes, particles, sprites, lines, ribbons, ... Geometry plane, cube, sphere, torus, 3D text and more Export/Import utilities to create Three.js-compatible JSON files from: Blender, CTM, FBX, 3D Max, and OBJ Wednesday, December 12, 12
  • 20. http://threejs.org/ https://github.com/mrdoob/three.js http://learningthreejs.com Wednesday, December 12, 12