SlideShare a Scribd company logo
WebGL para JavaScripters



                  Luz Caballero
Luz Caballero - @gerbille

        Web Opener
Agenda
• Que es WebGL?
• Para qué se puede usar?
• Cómo funciona?
• Lo que hay que saber para empezar
• Un poco de código
Qué es WebGL ?
OpenGL   OpenGL ES   WebGL
desktop   mobile
<canvas id=‘c’ width=‘100’ height=‘100’></canvas>


document.getElementById(‘c’).getContext(‘webgl’)
Para qué se puede usar?
•   Visualización de datos

•   Creative coding

•   Arte

•   Environments de diseño 3D

•   Videos de música

•   Graficación de funciones matemáticas

•   Modelado de objectos y espacios 3D

•   Creación de texturas

•   Simulaciones físicas

•   ...procesamiento rápido de cualquier tipo de
    datos
visualización de datos
creative coding
arte
environments de diseño 3D
videos de música
graficación de funciones matemáticas
modelado de objetos y espacios 3D
juegos
creación de texturas
simulaciones físicas
Cómo funciona?
Webgl para JavaScripters
JavaScript

WebGL JS API



               GPU (Compiled Program)
JavaScript


WebGL JS API


GLSL API        Vertex Shader




GLSL API       Fragment Shader
Lo que hay que saber
   para empezar
The 3D scene




          image source: http://computer.yourdictionary.com/graphics
Choosing a library
• Three.js
• PhiloGL
• GLGE
• J3D
• TDL
• ...
desktop   mobile
WebGL inspector
Un poco de código
Webgl para JavaScripters
<!DOCTYPE html>
<html>
  <head>
    <title>Learning WebGL lesson 11 in PhiloGL</title>
    <link href="path/to/file.css" type="text/css" rel="stylesheet"
media="screen" />
    <script src="path/to/PhiloGL.js"></script>
    <script src="path/to/index.js"></script>
  </head>
        
  <body onload="webGLStart();">
    <canvas id="lesson11-canvas" width="500" height="500"></canvas>
    <!-- more html elements here... -->
  </body>
</html>
function webGLStart() {
  var pos, $ = function(d) { return document.getElementById(d); };
    
  //Create moon
  var moon = new PhiloGL.O3D.Sphere({
    nlat: 30,
    nlong: 30,
    radius: 2,
    textures: 'moon.gif'
  });
  //Create application
  PhiloGL('lesson11-canvas', {
    camera: {
      position: {
        x: 0, y: 0, z: -7
      }
    },
    textures: {
      src: ['moon.gif'],
      parameters: [{
        name: 'TEXTURE_MAG_FILTER',
        value: 'LINEAR'
      }, {
        name: 'TEXTURE_MIN_FILTER',
        value: 'LINEAR_MIPMAP_NEAREST',
        generateMipmap: true
      }]
    },
    events: {
      onDragStart: function(e) {
        pos = {
          x: e.x,
          y: e.y
        };
      },
      onDragMove: function(e) {
        var z = this.camera.position.z,
        sign = Math.abs(z) / z;

          moon.rotation.y += -(pos.x - e.x) / 100;
          moon.rotation.x += sign * (pos.y - e.y) / 100;
          moon.update();
          pos.x = e.x;
          pos.y = e.y;
        },
        onMouseWheel: function(e) {
          e.stop();
          var camera = this.camera;
          camera.position.z += e.wheel;
          camera.update();
        }
      },
      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);
//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);
      }
    }
  });
}
Webgl para JavaScripters
<script>
    
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var FLOOR = 0;

var container;

var camera, scene;
var webglRenderer;

var zmesh, geometry;

var mouseX = 0, mouseY = 0;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

document.addEventListener( 'mousemove', onDocumentMouseMove, false );
init();
animate();
function init() {
  container = document.createElement( 'div' );
  document.body.appendChild( container );
            
  // camera
  camera = new THREE.PerspectiveCamera( 75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 100000 );
  camera.position.z = 75;
            
  // scene
  scene = new THREE.Scene();

  // lights
  var ambient = new THREE.AmbientLight( 0xffffff );
  scene.add( ambient );
            
  // more lights
  var directionalLight = new THREE.DirectionalLight( 0xffeedd );
  directionalLight.position.set( 0, -70, 100 ).normalize();
  scene.add( directionalLight );
}
// renderer
webglRenderer = new THREE.WebGLRenderer();
webglRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
webglRenderer.domElement.style.position = "relative";
container.appendChild( webglRenderer.domElement );

// loader
var loader = new THREE.JSONLoader(),
loader.load( { model: "obj/church/church.js", callback: createScene } );
                                         
function createScene( geometry ) {
  zmesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial() );
  zmesh.position.set( 0, 16, 0 );
  zmesh.scale.set( 1, 1, 1 );
  scene.add( zmesh );
}

function onDocumentMouseMove(event) {
  mouseX = ( event.clientX - windowHalfX );
  mouseY = ( event.clientY - windowHalfY );
}
function animate() {
  requestAnimationFrame( animate );
  render();
}

function render() {
  zmesh.rotation.set(-mouseY/500 + 1, -mouseX/200, 0);
  webglRenderer.render( scene, camera );
}
</script>                                         
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
•   WebGL-dev mailing list
Thanks!

@gerbille

More Related Content

KEY
Leaving Flatland: getting started with WebGL
KEY
5 tips for your HTML5 games
PDF
3D Web Programming [Thanh Loc Vo , CTO Epsilon Mobile ]
PPTX
AngularJS $Provide Service
PPTX
AngularJS Services
KEY
Barcamp GoogleMaps - praktické ukázky kódu
KEY
The Canvas Tag
PDF
Prototype UI
Leaving Flatland: getting started with WebGL
5 tips for your HTML5 games
3D Web Programming [Thanh Loc Vo , CTO Epsilon Mobile ]
AngularJS $Provide Service
AngularJS Services
Barcamp GoogleMaps - praktické ukázky kódu
The Canvas Tag
Prototype UI

What's hot (19)

PPTX
AngularJS Routing
KEY
Object-Oriented Javascript
PDF
Integrating Angular js & three.js
PDF
Javascript is your (Auto)mate
PPTX
The next step, part 2
PPTX
Developing Web Graphics with WebGL
PDF
Shibuya.js Lightning Talks
PPTX
AngularJS Compile Process
PPTX
SenchaCon 2016: Improve Workflow Driven Applications with Ext JS Draw Package...
PDF
Dion Almaer & Ben Galbraith - Build Once, Deploy Everywhere
PDF
Cyclejs introduction
PPTX
AngularJS Animations
PDF
Browsers with Wings
PDF
jQuery: Events, Animation, Ajax
PDF
What's new in iOS9
PPTX
Taming that client side mess with Backbone.js
PDF
How Kris Writes Symfony Apps
PDF
Processing and Processing.js
PDF
CQRS and Event Sourcing in a Symfony application
AngularJS Routing
Object-Oriented Javascript
Integrating Angular js & three.js
Javascript is your (Auto)mate
The next step, part 2
Developing Web Graphics with WebGL
Shibuya.js Lightning Talks
AngularJS Compile Process
SenchaCon 2016: Improve Workflow Driven Applications with Ext JS Draw Package...
Dion Almaer & Ben Galbraith - Build Once, Deploy Everywhere
Cyclejs introduction
AngularJS Animations
Browsers with Wings
jQuery: Events, Animation, Ajax
What's new in iOS9
Taming that client side mess with Backbone.js
How Kris Writes Symfony Apps
Processing and Processing.js
CQRS and Event Sourcing in a Symfony application
Ad

Viewers also liked (8)

PPT
творчество братьев леннен
KEY
Des interfaces futuristes utilisant des APIs web
PDF
Speed in the Opera mobile browsers
PDF
Speed in the Opera mobile browsers
DOCX
Growth model 2,5% de sodio
DOCX
Growth model con 0,5% de sodio
KEY
What's new in the Opera mobile browsers
PPT
Device dis(orientation)?
творчество братьев леннен
Des interfaces futuristes utilisant des APIs web
Speed in the Opera mobile browsers
Speed in the Opera mobile browsers
Growth model 2,5% de sodio
Growth model con 0,5% de sodio
What's new in the Opera mobile browsers
Device dis(orientation)?
Ad

Similar to Webgl para JavaScripters (20)

PDF
Leaving Flatland: Getting Started with WebGL- SXSW 2012
KEY
Getting Started with WebGL
PDF
WebGL and three.js
KEY
WebGL Awesomeness
ODP
Introduction to threejs
PPTX
HTML5DevConf 2013 (October): WebGL is a game changer!
PDF
"Graphical fun With WebGL shaders", Martin Splitt
PDF
Augmented reality in web rtc browser
PDF
Creating Applications with WebGL and Three.js
PDF
WebGL
PDF
Learning WebGLで学ぶWebGL入門
PDF
Introduction to Webgl by Rachel Prudden
PDF
ENEI16 - WebGL with Three.js
PDF
140716 : 同業前端聚會分享 - webgl 與 three.js
PDF
Installing Games Sucks, Learn WebGL
PDF
OpenGL Starter L02
PPTX
[JS EXPERIENCE 2018] Jogos em JavaScript com WebGL - Juliana Negreiros, Codem...
PDF
Getting Started with OpenGL ES
PDF
A Novice's Guide to WebGL
PDF
WebGL demos showcase
Leaving Flatland: Getting Started with WebGL- SXSW 2012
Getting Started with WebGL
WebGL and three.js
WebGL Awesomeness
Introduction to threejs
HTML5DevConf 2013 (October): WebGL is a game changer!
"Graphical fun With WebGL shaders", Martin Splitt
Augmented reality in web rtc browser
Creating Applications with WebGL and Three.js
WebGL
Learning WebGLで学ぶWebGL入門
Introduction to Webgl by Rachel Prudden
ENEI16 - WebGL with Three.js
140716 : 同業前端聚會分享 - webgl 與 three.js
Installing Games Sucks, Learn WebGL
OpenGL Starter L02
[JS EXPERIENCE 2018] Jogos em JavaScript com WebGL - Juliana Negreiros, Codem...
Getting Started with OpenGL ES
A Novice's Guide to WebGL
WebGL demos showcase

Recently uploaded (20)

PPT
Teaching material agriculture food technology
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Spectroscopy.pptx food analysis technology
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Empathic Computing: Creating Shared Understanding
PDF
Encapsulation theory and applications.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Getting Started with Data Integration: FME Form 101
PPTX
TLE Review Electricity (Electricity).pptx
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Teaching material agriculture food technology
Encapsulation_ Review paper, used for researhc scholars
Spectroscopy.pptx food analysis technology
NewMind AI Weekly Chronicles - August'25-Week II
Empathic Computing: Creating Shared Understanding
Encapsulation theory and applications.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Diabetes mellitus diagnosis method based random forest with bat algorithm
Advanced methodologies resolving dimensionality complications for autism neur...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Getting Started with Data Integration: FME Form 101
TLE Review Electricity (Electricity).pptx
SOPHOS-XG Firewall Administrator PPT.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
Network Security Unit 5.pdf for BCA BBA.
Programs and apps: productivity, graphics, security and other tools
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...

Webgl para JavaScripters

  • 1. WebGL para JavaScripters Luz Caballero
  • 2. Luz Caballero - @gerbille Web Opener
  • 3. Agenda • Que es WebGL? • Para qué se puede usar? • Cómo funciona? • Lo que hay que saber para empezar • Un poco de código
  • 5. OpenGL OpenGL ES WebGL
  • 6. desktop mobile
  • 7. <canvas id=‘c’ width=‘100’ height=‘100’></canvas> document.getElementById(‘c’).getContext(‘webgl’)
  • 8. Para qué se puede usar?
  • 9. Visualización de datos • Creative coding • Arte • Environments de diseño 3D • Videos de música • Graficación de funciones matemáticas • Modelado de objectos y espacios 3D • Creación de texturas • Simulaciones físicas • ...procesamiento rápido de cualquier tipo de datos
  • 12. arte
  • 16. modelado de objetos y espacios 3D
  • 22. JavaScript WebGL JS API GPU (Compiled Program)
  • 23. JavaScript WebGL JS API GLSL API Vertex Shader GLSL API Fragment Shader
  • 24. Lo que hay que saber para empezar
  • 25. The 3D scene image source: http://computer.yourdictionary.com/graphics
  • 26. Choosing a library • Three.js • PhiloGL • GLGE • J3D • TDL • ...
  • 27. desktop mobile
  • 29. Un poco de código
  • 31. <!DOCTYPE html> <html>   <head>     <title>Learning WebGL lesson 11 in PhiloGL</title>     <link href="path/to/file.css" type="text/css" rel="stylesheet" media="screen" />     <script src="path/to/PhiloGL.js"></script>     <script src="path/to/index.js"></script>   </head>            <body onload="webGLStart();">     <canvas id="lesson11-canvas" width="500" height="500"></canvas>     <!-- more html elements here... -->   </body> </html>
  • 32. function webGLStart() {   var pos, $ = function(d) { return document.getElementById(d); };        //Create moon   var moon = new PhiloGL.O3D.Sphere({     nlat: 30,     nlong: 30,     radius: 2,     textures: 'moon.gif'   });
  • 33.   //Create application   PhiloGL('lesson11-canvas', {     camera: {       position: {         x: 0, y: 0, z: -7       }     },     textures: {       src: ['moon.gif'],       parameters: [{         name: 'TEXTURE_MAG_FILTER',         value: 'LINEAR'       }, {         name: 'TEXTURE_MIN_FILTER',         value: 'LINEAR_MIPMAP_NEAREST',         generateMipmap: true       }]     },     events: {       onDragStart: function(e) {         pos = {           x: e.x,           y: e.y         };       },       onDragMove: function(e) {         var z = this.camera.position.z,         sign = Math.abs(z) / z;         moon.rotation.y += -(pos.x - e.x) / 100;         moon.rotation.x += sign * (pos.y - e.y) / 100;         moon.update();         pos.x = e.x;         pos.y = e.y;       },       onMouseWheel: function(e) {         e.stop();         var camera = this.camera;         camera.position.z += e.wheel;         camera.update();       }     },
  • 34.     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);
  • 35. //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);       }     }   }); }
  • 37. <script>      if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); var SCREEN_WIDTH = window.innerWidth; var SCREEN_HEIGHT = window.innerHeight; var FLOOR = 0; var container; var camera, scene; var webglRenderer; var zmesh, geometry; var mouseX = 0, mouseY = 0; var windowHalfX = window.innerWidth / 2; var windowHalfY = window.innerHeight / 2; document.addEventListener( 'mousemove', onDocumentMouseMove, false ); init(); animate();
  • 38. function init() {   container = document.createElement( 'div' );   document.body.appendChild( container );                // camera   camera = new THREE.PerspectiveCamera( 75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 100000 );   camera.position.z = 75;                // scene   scene = new THREE.Scene();   // lights   var ambient = new THREE.AmbientLight( 0xffffff );   scene.add( ambient );                // more lights   var directionalLight = new THREE.DirectionalLight( 0xffeedd );   directionalLight.position.set( 0, -70, 100 ).normalize();   scene.add( directionalLight ); }
  • 39. // renderer webglRenderer = new THREE.WebGLRenderer(); webglRenderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); webglRenderer.domElement.style.position = "relative"; container.appendChild( webglRenderer.domElement ); // loader var loader = new THREE.JSONLoader(), loader.load( { model: "obj/church/church.js", callback: createScene } );                                           function createScene( geometry ) {   zmesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial() );   zmesh.position.set( 0, 16, 0 );   zmesh.scale.set( 1, 1, 1 );   scene.add( zmesh ); } function onDocumentMouseMove(event) {   mouseX = ( event.clientX - windowHalfX );   mouseY = ( event.clientY - windowHalfY ); }
  • 40. function animate() {   requestAnimationFrame( animate );   render(); } function render() {   zmesh.rotation.set(-mouseY/500 + 1, -mouseX/200, 0);   webglRenderer.render( scene, camera ); } </script>                                         
  • 41. 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 • WebGL-dev mailing list