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

전형규, 프로젝트DH의 절차적 애니메이션 시스템, NDC2017
전형규, 프로젝트DH의 절차적 애니메이션 시스템, NDC2017전형규, 프로젝트DH의 절차적 애니메이션 시스템, NDC2017
전형규, 프로젝트DH의 절차적 애니메이션 시스템, NDC2017devCAT Studio, NEXON
 
Oculus Quest 2 on Mixed Reality Toolkit V2.5.0~ ハンドトラッキングする方法 ~
Oculus Quest 2 on Mixed Reality Toolkit V2.5.0~ ハンドトラッキングする方法 ~Oculus Quest 2 on Mixed Reality Toolkit V2.5.0~ ハンドトラッキングする方法 ~
Oculus Quest 2 on Mixed Reality Toolkit V2.5.0~ ハンドトラッキングする方法 ~Takahiro Miyaura
 
Ndc2010 김주복, v3. 마비노기2아키텍처리뷰
Ndc2010   김주복, v3. 마비노기2아키텍처리뷰Ndc2010   김주복, v3. 마비노기2아키텍처리뷰
Ndc2010 김주복, v3. 마비노기2아키텍처리뷰Jubok Kim
 
3 d 그래픽 엔진 비교
3 d 그래픽 엔진 비교3 d 그래픽 엔진 비교
3 d 그래픽 엔진 비교yoonhs306
 
[122]책에서는 맛볼 수 없는 HTML5 Canvas 이야기
[122]책에서는 맛볼 수 없는 HTML5 Canvas 이야기 [122]책에서는 맛볼 수 없는 HTML5 Canvas 이야기
[122]책에서는 맛볼 수 없는 HTML5 Canvas 이야기 NAVER D2
 
오픈소스로 쉽게 따라해보는 Unreal과 IoT 연계 및 개발 방법 소개.pdf
오픈소스로 쉽게 따라해보는 Unreal과 IoT 연계 및 개발 방법 소개.pdf오픈소스로 쉽게 따라해보는 Unreal과 IoT 연계 및 개발 방법 소개.pdf
오픈소스로 쉽게 따라해보는 Unreal과 IoT 연계 및 개발 방법 소개.pdfTae wook kang
 
Developing AR and VR Experiences with Unity
Developing AR and VR Experiences with UnityDeveloping AR and VR Experiences with Unity
Developing AR and VR Experiences with UnityMark Billinghurst
 
State of OpenGXT: 오픈소스 공간분석엔진
State of OpenGXT: 오픈소스 공간분석엔진State of OpenGXT: 오픈소스 공간분석엔진
State of OpenGXT: 오픈소스 공간분석엔진MinPa Lee
 
Azure kinect DKハンズオン
Azure kinect DKハンズオンAzure kinect DKハンズオン
Azure kinect DKハンズオンTakashi Yoshinaga
 
A-Framで始めるWebAR (Blenderハンズオンの続きver.)
A-Framで始めるWebAR (Blenderハンズオンの続きver.)A-Framで始めるWebAR (Blenderハンズオンの続きver.)
A-Framで始めるWebAR (Blenderハンズオンの続きver.)Takashi Yoshinaga
 
Game Programming 03 - Git Flow
Game Programming 03 - Git FlowGame Programming 03 - Git Flow
Game Programming 03 - Git FlowNick Pruehs
 
RenderTextureの正しいα値は?
RenderTextureの正しいα値は?RenderTextureの正しいα値は?
RenderTextureの正しいα値は?KLab Inc. / Tech
 
게임엔진과 공간정보 3D 콘텐츠 융합 : Cesium for Unreal
게임엔진과 공간정보 3D 콘텐츠 융합 : Cesium for Unreal게임엔진과 공간정보 3D 콘텐츠 융합 : Cesium for Unreal
게임엔진과 공간정보 3D 콘텐츠 융합 : Cesium for UnrealKyu-sung Choi
 
The Usage and Patterns of MagicOnion
The Usage and Patterns of MagicOnionThe Usage and Patterns of MagicOnion
The Usage and Patterns of MagicOnionYoshifumi Kawai
 
【Unity道場スペシャル 2017京都】最適化をする前に覚えておきたい技術
【Unity道場スペシャル 2017京都】最適化をする前に覚えておきたい技術【Unity道場スペシャル 2017京都】最適化をする前に覚えておきたい技術
【Unity道場スペシャル 2017京都】最適化をする前に覚えておきたい技術Unity Technologies Japan K.K.
 
アナザーエデンPC版リリースへの道のり 〜WFSにおけるマルチプラットフォーム対応の取り組み〜
アナザーエデンPC版リリースへの道のり 〜WFSにおけるマルチプラットフォーム対応の取り組み〜アナザーエデンPC版リリースへの道のり 〜WFSにおけるマルチプラットフォーム対応の取り組み〜
アナザーエデンPC版リリースへの道のり 〜WFSにおけるマルチプラットフォーム対応の取り組み〜gree_tech
 
WebXR: Introducing Mixed Reality and the Immersive Web - Peter O'Shaughnessy ...
WebXR: Introducing Mixed Reality and the Immersive Web - Peter O'Shaughnessy ...WebXR: Introducing Mixed Reality and the Immersive Web - Peter O'Shaughnessy ...
WebXR: Introducing Mixed Reality and the Immersive Web - Peter O'Shaughnessy ...Codemotion
 
김혁, <드래곤 하운드>의 PBR과 레이트레이싱 렌더링 기법, NDC2019
김혁, <드래곤 하운드>의 PBR과 레이트레이싱 렌더링 기법, NDC2019김혁, <드래곤 하운드>의 PBR과 레이트레이싱 렌더링 기법, NDC2019
김혁, <드래곤 하운드>의 PBR과 레이트레이싱 렌더링 기법, NDC2019devCAT Studio, NEXON
 
디지털 트윈(Digital Twin) - 도시와 공간정보 관점에서
디지털 트윈(Digital Twin) - 도시와 공간정보 관점에서디지털 트윈(Digital Twin) - 도시와 공간정보 관점에서
디지털 트윈(Digital Twin) - 도시와 공간정보 관점에서SANGHEE SHIN
 

What's hot (20)

전형규, 프로젝트DH의 절차적 애니메이션 시스템, NDC2017
전형규, 프로젝트DH의 절차적 애니메이션 시스템, NDC2017전형규, 프로젝트DH의 절차적 애니메이션 시스템, NDC2017
전형규, 프로젝트DH의 절차적 애니메이션 시스템, NDC2017
 
Oculus Quest 2 on Mixed Reality Toolkit V2.5.0~ ハンドトラッキングする方法 ~
Oculus Quest 2 on Mixed Reality Toolkit V2.5.0~ ハンドトラッキングする方法 ~Oculus Quest 2 on Mixed Reality Toolkit V2.5.0~ ハンドトラッキングする方法 ~
Oculus Quest 2 on Mixed Reality Toolkit V2.5.0~ ハンドトラッキングする方法 ~
 
Ndc2010 김주복, v3. 마비노기2아키텍처리뷰
Ndc2010   김주복, v3. 마비노기2아키텍처리뷰Ndc2010   김주복, v3. 마비노기2아키텍처리뷰
Ndc2010 김주복, v3. 마비노기2아키텍처리뷰
 
3 d 그래픽 엔진 비교
3 d 그래픽 엔진 비교3 d 그래픽 엔진 비교
3 d 그래픽 엔진 비교
 
[122]책에서는 맛볼 수 없는 HTML5 Canvas 이야기
[122]책에서는 맛볼 수 없는 HTML5 Canvas 이야기 [122]책에서는 맛볼 수 없는 HTML5 Canvas 이야기
[122]책에서는 맛볼 수 없는 HTML5 Canvas 이야기
 
오픈소스로 쉽게 따라해보는 Unreal과 IoT 연계 및 개발 방법 소개.pdf
오픈소스로 쉽게 따라해보는 Unreal과 IoT 연계 및 개발 방법 소개.pdf오픈소스로 쉽게 따라해보는 Unreal과 IoT 연계 및 개발 방법 소개.pdf
오픈소스로 쉽게 따라해보는 Unreal과 IoT 연계 및 개발 방법 소개.pdf
 
Developing AR and VR Experiences with Unity
Developing AR and VR Experiences with UnityDeveloping AR and VR Experiences with Unity
Developing AR and VR Experiences with Unity
 
State of OpenGXT: 오픈소스 공간분석엔진
State of OpenGXT: 오픈소스 공간분석엔진State of OpenGXT: 오픈소스 공간분석엔진
State of OpenGXT: 오픈소스 공간분석엔진
 
Azure kinect DKハンズオン
Azure kinect DKハンズオンAzure kinect DKハンズオン
Azure kinect DKハンズオン
 
A-Framで始めるWebAR (Blenderハンズオンの続きver.)
A-Framで始めるWebAR (Blenderハンズオンの続きver.)A-Framで始めるWebAR (Blenderハンズオンの続きver.)
A-Framで始めるWebAR (Blenderハンズオンの続きver.)
 
Game Programming 03 - Git Flow
Game Programming 03 - Git FlowGame Programming 03 - Git Flow
Game Programming 03 - Git Flow
 
RenderTextureの正しいα値は?
RenderTextureの正しいα値は?RenderTextureの正しいα値は?
RenderTextureの正しいα値は?
 
게임엔진과 공간정보 3D 콘텐츠 융합 : Cesium for Unreal
게임엔진과 공간정보 3D 콘텐츠 융합 : Cesium for Unreal게임엔진과 공간정보 3D 콘텐츠 융합 : Cesium for Unreal
게임엔진과 공간정보 3D 콘텐츠 융합 : Cesium for Unreal
 
The Usage and Patterns of MagicOnion
The Usage and Patterns of MagicOnionThe Usage and Patterns of MagicOnion
The Usage and Patterns of MagicOnion
 
WebGL
WebGLWebGL
WebGL
 
【Unity道場スペシャル 2017京都】最適化をする前に覚えておきたい技術
【Unity道場スペシャル 2017京都】最適化をする前に覚えておきたい技術【Unity道場スペシャル 2017京都】最適化をする前に覚えておきたい技術
【Unity道場スペシャル 2017京都】最適化をする前に覚えておきたい技術
 
アナザーエデンPC版リリースへの道のり 〜WFSにおけるマルチプラットフォーム対応の取り組み〜
アナザーエデンPC版リリースへの道のり 〜WFSにおけるマルチプラットフォーム対応の取り組み〜アナザーエデンPC版リリースへの道のり 〜WFSにおけるマルチプラットフォーム対応の取り組み〜
アナザーエデンPC版リリースへの道のり 〜WFSにおけるマルチプラットフォーム対応の取り組み〜
 
WebXR: Introducing Mixed Reality and the Immersive Web - Peter O'Shaughnessy ...
WebXR: Introducing Mixed Reality and the Immersive Web - Peter O'Shaughnessy ...WebXR: Introducing Mixed Reality and the Immersive Web - Peter O'Shaughnessy ...
WebXR: Introducing Mixed Reality and the Immersive Web - Peter O'Shaughnessy ...
 
김혁, <드래곤 하운드>의 PBR과 레이트레이싱 렌더링 기법, NDC2019
김혁, <드래곤 하운드>의 PBR과 레이트레이싱 렌더링 기법, NDC2019김혁, <드래곤 하운드>의 PBR과 레이트레이싱 렌더링 기법, NDC2019
김혁, <드래곤 하운드>의 PBR과 레이트레이싱 렌더링 기법, NDC2019
 
디지털 트윈(Digital Twin) - 도시와 공간정보 관점에서
디지털 트윈(Digital Twin) - 도시와 공간정보 관점에서디지털 트윈(Digital Twin) - 도시와 공간정보 관점에서
디지털 트윈(Digital Twin) - 도시와 공간정보 관점에서
 

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
 

Similar to WebGL and three.js (20)

Intro to Three.js
Intro to Three.jsIntro to Three.js
Intro to Three.js
 
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
 

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