SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Programación de videojuegos HTML5
¿Quién soy?
              Jesús David García Gómez
              UX Developer at Plain Concepts
              dgarcia@plainconcepts.com
              #htmltour

              Proyectos destacados:




                 www.plainconcepts.com
¿Quién soy?
                            Fernando Oteros Pastrana
                            Desarrollador PHP
                            Desarrollador HTML5 / Javascript
                            Desarrollador Flash AS3


                            Proyectos destacados:




     Twitter: @sh4wner
                                Project Prometheus             The Hunger Games
foteros@plainconcepts.com

                               www.plainconcepts.com
Preguntas / Dudas / Sugerencias




              #htmltour
        http://sh4wn.net/htmltour/demos_html5.zip
SVG y Canvas
SVG

  • SVG son las siglas de Scalable Vector Graphics

  • Es un lenguaje para describir gráficos en 2D en XML.

  • Con HTML5, podemos agregar un SVG al DOM

  • Acceso a sus elementos.
SVG - Sintaxis



   <svg xmlns="http://www.w3.org/2000/svg" height="200px">
   …
   </svg>
SVG - Componentes

  • Circle:
   <circle cx="100" cy="100" r="40" fill="red" />



  • Rect:
   <rect x="50" y="140" width="100" height="20" fill="green" />


  • Line:
   <line x1="40" y1="40" x2="40" y2="170" style="stroke: red; stroke-width: 2" />
SVG – Más Componentes
  • Ellipse
   <ellipse cx="100" cy="50" rx="100" ry="50" fill="url(#gradient)" />



  • Polygon
   <polygon points="50,140 150,140, 100,170" fill="blue" />



  • Polyline
   <polyline points="0,0 0,190 200,190 200,0 0,0" fill="transparent" style="stroke:
   red; stroke-width: 3" />
Canvas


  • El elemento <canvas> se utiliza para pintar gráficos.

  • Es un contenedor, debemos usar scripts para pintar los gráficos en el.

  • Podemos tener más de un <canvas> en nuestra web
Canvas – Modo de pintado


   • Canvas utiliza “modo inmediato”

   • SVG, Flash y Silverlight utilizan “modo retenido”
Canvas - Contexto


   var canvas = document.getElementById("miCanvas");

   var context = canvas.getContext("2d");
Canvas – Comprobar compatibilidad


   function IsCanvasCompatible() {
       var canvas = document.getElementById("miCanvas");
       if (!canvas || !canvas.getContext)
            return false;
       else
            return true;
   }
Canvas – Elementos básicos
   • Texto
               context.fillText(today, 150, 10);
               context.strokeText(today, 150, 10);


   • Rectángulos
               context.fillRect(0, 0, 150, 75);
               context.strokeRect(0, 0, 150, 75);
               context.clearRect(0, 0, 150, 75);
Canvas – Más elementos básicos

   • Imágenes

             context.drawImage(newImage, 200, 100);


   • Paths
                    context.beginPath();
                    context.closePath();
Canvas - Path
   • Lineas
              context.beginPath();
              context.moveTo(10, 10);
              context.lineTo(20, 20);
              context.stroke();
              context.closePath();

   • Arcos
              context.beginPath();
              context.arc(100, 100, 50, 0, Math.PI);
              context.fill();
              context.closePath();
Canvas - Formato
   context.textAlign = "center";
   context.measureText("texto").width;
   context.font = "60px Arial";
   context.fillStyle = "red";
   context.strokeStyle = "red";
   context.shadowBlur = 10;
   context.shadowColor = "black";
Canvas – Más formatos


   context.lineWidth = lineWidth * 2;
   context.lineJoin = "round";
   var gradient = context.createLinearGradient(x, y, dx, dy);
   gradient.addColorStop(0, primaryColor);
   gradient.addColorStop(1, secondaryColor);
Programación de videojuegos HTML5
Introducción
 • <CANVAS></CANVAS>
 • <SVG></SVG>
 • <AUDIO></AUDIO>
 • <VIDEO></VIDEO>
 • Transiciones CSS
 • LocalStorage
 • WebSockets
Volviendo al Old School
  • Limitaciones de los actuales navegadores

  • Viejas técnicas y recursos cómo:
     • Sprites para animaciones
     • Repetición de fondos.
Estructura básica de los juegos html5
   <!DOCTYPE html>
   <html>
   <head>
   <meta http-equiv="content-type" content="text/html; charset=utf-8">
   <meta charset="utf-8">
   <title>Demo 01</title>
   <link type="text/css" rel="stylesheet" href="style.css">
   <script src="demo01.js"></script>
   </head>
   <body onload="game.init()">
           <canvas id="canvas" class="gameLayer" width=“700" height=“500"></canvas>
   </body>
   </html>



   Elemento CANVAS                  Hoja de estilo                  JS
Game.js
       var game = (function () {
                  var canvas,
                 canvasCtx;
                  //Initialize: Crea los objetos que vamos a usar en el juego.
                  function initialize() {
                      //Crear objetos
                  }
                  //Loop: Se ejecuta en cada ciclo actualizando objetos y pintando el canvas .
                  function loop() {
                      update();
                      draw();
                  }
                  //Update: Actualiza cada uno de los objetos de nuestro juego, su posición, disparos, etc…
                  function update() {
                      player.update();
                  }
                  //Draw: Pinta en el canvas nuestros objetos
                  function draw() {
                      ctx.drawImage(buffer, 0, 0);
                  }
                  return {
                      init: initialize
                  }
              })();
   .
GameLoop: setTimeOut vs RequestAnimationFrame

 GameLoop o bucle principal
     Llama a la función Update y Draw.

 Antes: setTimeOut(function,time);

 Con html5: requestAnimationFrame (function);
 Hasta que no termina de realizar todas las operaciones no vuelve a ser
 llamado, optimizando de esta manera la experiencia de usuario.
Uso de requestAnimationFrame
 this.loop = function () {
             this.update();
             this.draw();
             gameInterval = window.requestAnimationFrame(loop);
         }
         this.update = function () {
             player.update();
         }

        gameInterval = window.requestAnimationFrame(loop);


 Una vez inicializado el requestAnimationFrame, lo volvemos a
 llamar desde el metodo update cuando finaliza cada ciclo.

 Snippet incluído en la demo.
Pintando nuestro juego
   Función “Draw” llamada desde el bucle principal.


  this.draw = function () {
              this.canvasCtx.clearRect(0, 0,
  this.canvas.width, this.canvas.height);
              this.canvasCtx.beginPath();
              this.canvasCtx.rect(this.rectangulo.x,
  this.rectangulo.y, this.rectangulo.w, this.rectangulo.h);
              this.canvasCtx.fillStyle = "#000";
              this.canvasCtx.closePath();
              this.canvasCtx.fill();
          }
Canvas buffer
   Canvas oculto.
   Lo copiamos al Canvas visible.

   Evita la sensación de flickering (parpadeo).

   this.bufferCtx.clearRect(0, 0, this.buffer.width, this.buffer.height);
           this.bufferCtx.beginPath();
           this.bufferCtx.rect(this.rectangulo.x, this.rectangulo.y,
   this.rectangulo.w, this.rectangulo.h); this.bufferCtx.fillStyle = "#000";
           this.bufferCtx.closePath();
           this.bufferCtx.fill();
           this.canvasCtx.clearRect(0, 0, this.buffer.width, this.buffer.height);
   this.canvasCtx.drawImage(this.buffer, 0, 0);
Events && keyHandlers
  window.addEventListener('keydown', doKeyDown, true);
          function doKeyDown(evt) {
              switch (evt.keyCode) {
                  case 38: /* Up arrow was pressed */
                      //acciones de salto;
                      player.salta();
                      break;
                  case 40: /* Down arrow was pressed */
                      //agacharse;
                      player.agacha();
                      break;
                  case 37: /* Left arrow was pressed */
                      //caminar;
                      player.move(1);
                      break;
                  case 39: /* Right arrow was pressed */
                      //caminar;
                      player.move(2);
                      break;
              }
          }
Otros eventos
Animando Sprites
  http://www.w3schools.com/html5/canvas_drawimage.asp

      game.bufferCanvasCtx.drawImage(                   Función drawImage.
          spriteObject,                                 Permite desplazarnos a un punto de una imagen, y
          posicionXdelPuntero,                          seleccionar una región a mostrar.
          posicionYdelPuntero,
          anchoSprite,
          altoSprite,
          posicionXenCanvas,
          positionYenCanvas,
          anchoEnCanvas,
          altoEnCanvas);
       }
Sonidos

  var audio = document.createElement("audio");   //también sirve new Audio();
  audio.oncanplaythrought=function(){
   //sonidoCargado.
   audio.play();
  }
  audio.src = “sound.mp3”;
Video en HTML5
    <video loop controls id="thevideo" width="320" height="240" preload="auto">
            <source src="muirbeach.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' >
            <source src="muirbeach.webm"type='video/webm; codecs="vp8, vorbis"' >
            <source src="muirbeach.ogg" type='video/ogg; codecs="theora, vorbis"'>
        </video>
Video con canal Alpha
   function processFrame() {
       buffer.drawImage(video, 0, 0);
       var image = buffer.getImageData(0, 0, width, height),
     imageData = image.data,
     alphaData = buffer.getImageData(0, height, width, height).data;
       for (var i = 3, len = imageData.length; i < len; i = i + 4) {
           imageData[i] = alphaData[i - 1];
       }
       output.putImageData(image, 0, 0, 0, 0, width, height);
   }

                                http://jakearchibald.com/scratch/alphavid/
                                           ImageData Structure:
Librerías 3D

       WebGL:
                three.js http://mrdoob.github.com/three.js/




       Otras:
                WaveJS http://www.plainconcepts.com/wavejs
PROJECT PROMETHEUS




     http://www.projectprometheus.com/trainingcenter/
THE HUNGER GAMES
Preguntas / Dudas / Sugerencias




              #htmltour
        http://sh4wn.net/htmltour/demos_html5.zip

Weitere ähnliche Inhalte

Andere mochten auch

Andere mochten auch (13)

Security in MVC Core by Hugo Biarge
Security in MVC Core by Hugo BiargeSecurity in MVC Core by Hugo Biarge
Security in MVC Core by Hugo Biarge
 
Net core path by Ibon Landa
Net core path by Ibon LandaNet core path by Ibon Landa
Net core path by Ibon Landa
 
Cross-premises: integrando redes e infraestructura con Microsoft Azure
Cross-premises: integrando redes e infraestructura con Microsoft AzureCross-premises: integrando redes e infraestructura con Microsoft Azure
Cross-premises: integrando redes e infraestructura con Microsoft Azure
 
Entity Framework Core by Unai Zorrilla
Entity Framework Core by Unai ZorrillaEntity Framework Core by Unai Zorrilla
Entity Framework Core by Unai Zorrilla
 
Realtime Apps en .NET Core by Carlos Landeras y Manuel Rodrigo Cabello
Realtime Apps en .NET Core by Carlos Landeras y Manuel Rodrigo CabelloRealtime Apps en .NET Core by Carlos Landeras y Manuel Rodrigo Cabello
Realtime Apps en .NET Core by Carlos Landeras y Manuel Rodrigo Cabello
 
ASP.NET MVC Core by Eduard Tomàs
ASP.NET MVC Core by Eduard TomàsASP.NET MVC Core by Eduard Tomàs
ASP.NET MVC Core by Eduard Tomàs
 
Push notifications
Push notificationsPush notifications
Push notifications
 
Diseña tus aplicaciones multiplataforma
Diseña tus aplicaciones multiplataformaDiseña tus aplicaciones multiplataforma
Diseña tus aplicaciones multiplataforma
 
Microsoft Intune y Gestión de Identidad Corporativa
Microsoft Intune y Gestión de Identidad Corporativa Microsoft Intune y Gestión de Identidad Corporativa
Microsoft Intune y Gestión de Identidad Corporativa
 
Azure API Management
Azure API ManagementAzure API Management
Azure API Management
 
Analitics: Monitoriza tus aplicaciones móviles
Analitics: Monitoriza tus aplicaciones móvilesAnalitics: Monitoriza tus aplicaciones móviles
Analitics: Monitoriza tus aplicaciones móviles
 
Testing Xamarin Test Cloud
Testing Xamarin Test CloudTesting Xamarin Test Cloud
Testing Xamarin Test Cloud
 
Single Sign On e IdPs: Active Directory Federation Services (ADFS)
Single Sign On e IdPs: Active Directory Federation Services (ADFS)Single Sign On e IdPs: Active Directory Federation Services (ADFS)
Single Sign On e IdPs: Active Directory Federation Services (ADFS)
 

Ähnlich wie HTML Tour - Programación de Videojuegos HTML5

Codigo ejemplo j2 me
Codigo ejemplo   j2 meCodigo ejemplo   j2 me
Codigo ejemplo j2 me
Oscar Eduardo
 

Ähnlich wie HTML Tour - Programación de Videojuegos HTML5 (20)

Html5 css3
Html5 css3Html5 css3
Html5 css3
 
html5-css3
html5-css3html5-css3
html5-css3
 
Ria 03-html5-css3
Ria 03-html5-css3Ria 03-html5-css3
Ria 03-html5-css3
 
(Muy breve) Introduccion a jQuery
(Muy breve) Introduccion a jQuery(Muy breve) Introduccion a jQuery
(Muy breve) Introduccion a jQuery
 
Como crear un blog 2 parte
Como crear un blog 2 parteComo crear un blog 2 parte
Como crear un blog 2 parte
 
Canvas
CanvasCanvas
Canvas
 
Canvas
CanvasCanvas
Canvas
 
Estilo & CSS3
Estilo & CSS3Estilo & CSS3
Estilo & CSS3
 
Unidad 3 AJAX
Unidad 3 AJAX Unidad 3 AJAX
Unidad 3 AJAX
 
Unidad3ajax
Unidad3ajaxUnidad3ajax
Unidad3ajax
 
Canvas
CanvasCanvas
Canvas
 
09. Creando interfaces de usuario animadas y adaptables
09. Creando interfaces de usuario animadas y adaptables09. Creando interfaces de usuario animadas y adaptables
09. Creando interfaces de usuario animadas y adaptables
 
Xna game studio presentación 02
Xna game studio   presentación 02Xna game studio   presentación 02
Xna game studio presentación 02
 
02. Interactuando con controles de UI
02. Interactuando con controles de UI02. Interactuando con controles de UI
02. Interactuando con controles de UI
 
Conoce HTML5 y CSS3
Conoce HTML5 y CSS3Conoce HTML5 y CSS3
Conoce HTML5 y CSS3
 
Gwt III - Avanzado
Gwt III - AvanzadoGwt III - Avanzado
Gwt III - Avanzado
 
Creando controles para Xamarin.Forms
Creando controles para Xamarin.FormsCreando controles para Xamarin.Forms
Creando controles para Xamarin.Forms
 
Javascript en proyectos reales: jQuery
Javascript en proyectos reales: jQueryJavascript en proyectos reales: jQuery
Javascript en proyectos reales: jQuery
 
HTML 5 & WebGL (Spanish Version)
HTML 5 & WebGL (Spanish Version)HTML 5 & WebGL (Spanish Version)
HTML 5 & WebGL (Spanish Version)
 
Codigo ejemplo j2 me
Codigo ejemplo   j2 meCodigo ejemplo   j2 me
Codigo ejemplo j2 me
 

Mehr von Plain Concepts

DotNet 2019 | Sherry List - Azure Cognitive Services with Native Script
DotNet 2019 | Sherry List - Azure Cognitive Services with Native ScriptDotNet 2019 | Sherry List - Azure Cognitive Services with Native Script
DotNet 2019 | Sherry List - Azure Cognitive Services with Native Script
Plain Concepts
 
El camino a las Cloud Native Apps - Introduction
El camino a las Cloud Native Apps - IntroductionEl camino a las Cloud Native Apps - Introduction
El camino a las Cloud Native Apps - Introduction
Plain Concepts
 
El camino a las Cloud Native Apps - Azure AI
El camino a las Cloud Native Apps - Azure AIEl camino a las Cloud Native Apps - Azure AI
El camino a las Cloud Native Apps - Azure AI
Plain Concepts
 

Mehr von Plain Concepts (20)

R y Python con Power BI, la ciencia y el análisis de datos, juntos
R y Python con Power BI, la ciencia y el análisis de datos, juntosR y Python con Power BI, la ciencia y el análisis de datos, juntos
R y Python con Power BI, la ciencia y el análisis de datos, juntos
 
Video kills the radio star: e-mail is crap and needed disruption
 Video kills the radio star: e-mail is crap and needed disruption Video kills the radio star: e-mail is crap and needed disruption
Video kills the radio star: e-mail is crap and needed disruption
 
Cómo redefinir tu organización con IA
Cómo redefinir tu organización con IACómo redefinir tu organización con IA
Cómo redefinir tu organización con IA
 
Dx29: assisting genetic disease diagnosis with physician-focused AI pipelines
Dx29: assisting genetic disease diagnosis with physician-focused AI pipelinesDx29: assisting genetic disease diagnosis with physician-focused AI pipelines
Dx29: assisting genetic disease diagnosis with physician-focused AI pipelines
 
¿Qué es real? Cuando la IA intenta engañar al ojo humano
¿Qué es real? Cuando la IA intenta engañar al ojo humano¿Qué es real? Cuando la IA intenta engañar al ojo humano
¿Qué es real? Cuando la IA intenta engañar al ojo humano
 
Inteligencia artificial para detectar el cáncer de mama
Inteligencia artificial para  detectar el cáncer de mamaInteligencia artificial para  detectar el cáncer de mama
Inteligencia artificial para detectar el cáncer de mama
 
¿Está tu compañía preparada para el reto de la Inteligencia Artificial?
¿Está tu compañía preparada para el reto de la Inteligencia Artificial?¿Está tu compañía preparada para el reto de la Inteligencia Artificial?
¿Está tu compañía preparada para el reto de la Inteligencia Artificial?
 
Cognitive Services en acción
Cognitive Services en acciónCognitive Services en acción
Cognitive Services en acción
 
El Hogar Inteligente. De los datos de IoT a los hábitos de una familia a trav...
El Hogar Inteligente. De los datos de IoT a los hábitos de una familia a trav...El Hogar Inteligente. De los datos de IoT a los hábitos de una familia a trav...
El Hogar Inteligente. De los datos de IoT a los hábitos de una familia a trav...
 
What if AI was your daughter?
What if AI was your daughter?What if AI was your daughter?
What if AI was your daughter?
 
Recomendación Basada en Contenidos con Deep Learning: Qué queríamos hacer, Qu...
Recomendación Basada en Contenidos con Deep Learning: Qué queríamos hacer, Qu...Recomendación Basada en Contenidos con Deep Learning: Qué queríamos hacer, Qu...
Recomendación Basada en Contenidos con Deep Learning: Qué queríamos hacer, Qu...
 
Revolucionando la experiencia de cliente con Big Data e IA
Revolucionando la experiencia de cliente con Big Data e IARevolucionando la experiencia de cliente con Big Data e IA
Revolucionando la experiencia de cliente con Big Data e IA
 
IA Score en InfoJobs
IA Score en InfoJobsIA Score en InfoJobs
IA Score en InfoJobs
 
Recuperación de información para solicitantes de empleo
Recuperación de información para solicitantes de empleoRecuperación de información para solicitantes de empleo
Recuperación de información para solicitantes de empleo
 
La nueva revolución Industrial: Inteligencia Artificial & IoT Edge
La nueva revolución Industrial: Inteligencia Artificial & IoT EdgeLa nueva revolución Industrial: Inteligencia Artificial & IoT Edge
La nueva revolución Industrial: Inteligencia Artificial & IoT Edge
 
DotNet 2019 | Sherry List - Azure Cognitive Services with Native Script
DotNet 2019 | Sherry List - Azure Cognitive Services with Native ScriptDotNet 2019 | Sherry List - Azure Cognitive Services with Native Script
DotNet 2019 | Sherry List - Azure Cognitive Services with Native Script
 
DotNet 2019 | Quique Fernández - Potenciando VUE con TypeScript, Inversify, V...
DotNet 2019 | Quique Fernández - Potenciando VUE con TypeScript, Inversify, V...DotNet 2019 | Quique Fernández - Potenciando VUE con TypeScript, Inversify, V...
DotNet 2019 | Quique Fernández - Potenciando VUE con TypeScript, Inversify, V...
 
DotNet 2019 | Daniela Solís y Manuel Rodrigo Cabello - IoT, una Raspberry Pi ...
DotNet 2019 | Daniela Solís y Manuel Rodrigo Cabello - IoT, una Raspberry Pi ...DotNet 2019 | Daniela Solís y Manuel Rodrigo Cabello - IoT, una Raspberry Pi ...
DotNet 2019 | Daniela Solís y Manuel Rodrigo Cabello - IoT, una Raspberry Pi ...
 
El camino a las Cloud Native Apps - Introduction
El camino a las Cloud Native Apps - IntroductionEl camino a las Cloud Native Apps - Introduction
El camino a las Cloud Native Apps - Introduction
 
El camino a las Cloud Native Apps - Azure AI
El camino a las Cloud Native Apps - Azure AIEl camino a las Cloud Native Apps - Azure AI
El camino a las Cloud Native Apps - Azure AI
 

Kürzlich hochgeladen

redes informaticas en una oficina administrativa
redes informaticas en una oficina administrativaredes informaticas en una oficina administrativa
redes informaticas en una oficina administrativa
nicho110
 

Kürzlich hochgeladen (11)

Innovaciones tecnologicas en el siglo 21
Innovaciones tecnologicas en el siglo 21Innovaciones tecnologicas en el siglo 21
Innovaciones tecnologicas en el siglo 21
 
Guia Basica para bachillerato de Circuitos Basicos
Guia Basica para bachillerato de Circuitos BasicosGuia Basica para bachillerato de Circuitos Basicos
Guia Basica para bachillerato de Circuitos Basicos
 
How to use Redis with MuleSoft. A quick start presentation.
How to use Redis with MuleSoft. A quick start presentation.How to use Redis with MuleSoft. A quick start presentation.
How to use Redis with MuleSoft. A quick start presentation.
 
Avances tecnológicos del siglo XXI 10-07 eyvana
Avances tecnológicos del siglo XXI 10-07 eyvanaAvances tecnológicos del siglo XXI 10-07 eyvana
Avances tecnológicos del siglo XXI 10-07 eyvana
 
Buenos_Aires_Meetup_Redis_20240430_.pptx
Buenos_Aires_Meetup_Redis_20240430_.pptxBuenos_Aires_Meetup_Redis_20240430_.pptx
Buenos_Aires_Meetup_Redis_20240430_.pptx
 
PROYECTO FINAL. Tutorial para publicar en SlideShare.pptx
PROYECTO FINAL. Tutorial para publicar en SlideShare.pptxPROYECTO FINAL. Tutorial para publicar en SlideShare.pptx
PROYECTO FINAL. Tutorial para publicar en SlideShare.pptx
 
investigación de los Avances tecnológicos del siglo XXI
investigación de los Avances tecnológicos del siglo XXIinvestigación de los Avances tecnológicos del siglo XXI
investigación de los Avances tecnológicos del siglo XXI
 
Avances tecnológicos del siglo XXI y ejemplos de estos
Avances tecnológicos del siglo XXI y ejemplos de estosAvances tecnológicos del siglo XXI y ejemplos de estos
Avances tecnológicos del siglo XXI y ejemplos de estos
 
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptxEVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
EVOLUCION DE LA TECNOLOGIA Y SUS ASPECTOSpptx
 
redes informaticas en una oficina administrativa
redes informaticas en una oficina administrativaredes informaticas en una oficina administrativa
redes informaticas en una oficina administrativa
 
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
Resistencia extrema al cobre por un consorcio bacteriano conformado por Sulfo...
 

HTML Tour - Programación de Videojuegos HTML5

  • 2. ¿Quién soy? Jesús David García Gómez UX Developer at Plain Concepts dgarcia@plainconcepts.com #htmltour Proyectos destacados: www.plainconcepts.com
  • 3. ¿Quién soy? Fernando Oteros Pastrana Desarrollador PHP Desarrollador HTML5 / Javascript Desarrollador Flash AS3 Proyectos destacados: Twitter: @sh4wner Project Prometheus The Hunger Games foteros@plainconcepts.com www.plainconcepts.com
  • 4. Preguntas / Dudas / Sugerencias #htmltour http://sh4wn.net/htmltour/demos_html5.zip
  • 6. SVG • SVG son las siglas de Scalable Vector Graphics • Es un lenguaje para describir gráficos en 2D en XML. • Con HTML5, podemos agregar un SVG al DOM • Acceso a sus elementos.
  • 7. SVG - Sintaxis <svg xmlns="http://www.w3.org/2000/svg" height="200px"> … </svg>
  • 8. SVG - Componentes • Circle: <circle cx="100" cy="100" r="40" fill="red" /> • Rect: <rect x="50" y="140" width="100" height="20" fill="green" /> • Line: <line x1="40" y1="40" x2="40" y2="170" style="stroke: red; stroke-width: 2" />
  • 9. SVG – Más Componentes • Ellipse <ellipse cx="100" cy="50" rx="100" ry="50" fill="url(#gradient)" /> • Polygon <polygon points="50,140 150,140, 100,170" fill="blue" /> • Polyline <polyline points="0,0 0,190 200,190 200,0 0,0" fill="transparent" style="stroke: red; stroke-width: 3" />
  • 10. Canvas • El elemento <canvas> se utiliza para pintar gráficos. • Es un contenedor, debemos usar scripts para pintar los gráficos en el. • Podemos tener más de un <canvas> en nuestra web
  • 11. Canvas – Modo de pintado • Canvas utiliza “modo inmediato” • SVG, Flash y Silverlight utilizan “modo retenido”
  • 12. Canvas - Contexto var canvas = document.getElementById("miCanvas"); var context = canvas.getContext("2d");
  • 13. Canvas – Comprobar compatibilidad function IsCanvasCompatible() { var canvas = document.getElementById("miCanvas"); if (!canvas || !canvas.getContext) return false; else return true; }
  • 14. Canvas – Elementos básicos • Texto context.fillText(today, 150, 10); context.strokeText(today, 150, 10); • Rectángulos context.fillRect(0, 0, 150, 75); context.strokeRect(0, 0, 150, 75); context.clearRect(0, 0, 150, 75);
  • 15. Canvas – Más elementos básicos • Imágenes context.drawImage(newImage, 200, 100); • Paths context.beginPath(); context.closePath();
  • 16. Canvas - Path • Lineas context.beginPath(); context.moveTo(10, 10); context.lineTo(20, 20); context.stroke(); context.closePath(); • Arcos context.beginPath(); context.arc(100, 100, 50, 0, Math.PI); context.fill(); context.closePath();
  • 17. Canvas - Formato context.textAlign = "center"; context.measureText("texto").width; context.font = "60px Arial"; context.fillStyle = "red"; context.strokeStyle = "red"; context.shadowBlur = 10; context.shadowColor = "black";
  • 18. Canvas – Más formatos context.lineWidth = lineWidth * 2; context.lineJoin = "round"; var gradient = context.createLinearGradient(x, y, dx, dy); gradient.addColorStop(0, primaryColor); gradient.addColorStop(1, secondaryColor);
  • 20. Introducción • <CANVAS></CANVAS> • <SVG></SVG> • <AUDIO></AUDIO> • <VIDEO></VIDEO> • Transiciones CSS • LocalStorage • WebSockets
  • 21. Volviendo al Old School • Limitaciones de los actuales navegadores • Viejas técnicas y recursos cómo: • Sprites para animaciones • Repetición de fondos.
  • 22. Estructura básica de los juegos html5 <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta charset="utf-8"> <title>Demo 01</title> <link type="text/css" rel="stylesheet" href="style.css"> <script src="demo01.js"></script> </head> <body onload="game.init()"> <canvas id="canvas" class="gameLayer" width=“700" height=“500"></canvas> </body> </html> Elemento CANVAS Hoja de estilo JS
  • 23. Game.js var game = (function () { var canvas, canvasCtx; //Initialize: Crea los objetos que vamos a usar en el juego. function initialize() { //Crear objetos } //Loop: Se ejecuta en cada ciclo actualizando objetos y pintando el canvas . function loop() { update(); draw(); } //Update: Actualiza cada uno de los objetos de nuestro juego, su posición, disparos, etc… function update() { player.update(); } //Draw: Pinta en el canvas nuestros objetos function draw() { ctx.drawImage(buffer, 0, 0); } return { init: initialize } })(); .
  • 24. GameLoop: setTimeOut vs RequestAnimationFrame GameLoop o bucle principal Llama a la función Update y Draw. Antes: setTimeOut(function,time); Con html5: requestAnimationFrame (function); Hasta que no termina de realizar todas las operaciones no vuelve a ser llamado, optimizando de esta manera la experiencia de usuario.
  • 25. Uso de requestAnimationFrame this.loop = function () { this.update(); this.draw(); gameInterval = window.requestAnimationFrame(loop); } this.update = function () { player.update(); } gameInterval = window.requestAnimationFrame(loop); Una vez inicializado el requestAnimationFrame, lo volvemos a llamar desde el metodo update cuando finaliza cada ciclo. Snippet incluído en la demo.
  • 26. Pintando nuestro juego Función “Draw” llamada desde el bucle principal. this.draw = function () { this.canvasCtx.clearRect(0, 0, this.canvas.width, this.canvas.height); this.canvasCtx.beginPath(); this.canvasCtx.rect(this.rectangulo.x, this.rectangulo.y, this.rectangulo.w, this.rectangulo.h); this.canvasCtx.fillStyle = "#000"; this.canvasCtx.closePath(); this.canvasCtx.fill(); }
  • 27. Canvas buffer Canvas oculto. Lo copiamos al Canvas visible. Evita la sensación de flickering (parpadeo). this.bufferCtx.clearRect(0, 0, this.buffer.width, this.buffer.height); this.bufferCtx.beginPath(); this.bufferCtx.rect(this.rectangulo.x, this.rectangulo.y, this.rectangulo.w, this.rectangulo.h); this.bufferCtx.fillStyle = "#000"; this.bufferCtx.closePath(); this.bufferCtx.fill(); this.canvasCtx.clearRect(0, 0, this.buffer.width, this.buffer.height); this.canvasCtx.drawImage(this.buffer, 0, 0);
  • 28. Events && keyHandlers window.addEventListener('keydown', doKeyDown, true); function doKeyDown(evt) { switch (evt.keyCode) { case 38: /* Up arrow was pressed */ //acciones de salto; player.salta(); break; case 40: /* Down arrow was pressed */ //agacharse; player.agacha(); break; case 37: /* Left arrow was pressed */ //caminar; player.move(1); break; case 39: /* Right arrow was pressed */ //caminar; player.move(2); break; } }
  • 30. Animando Sprites http://www.w3schools.com/html5/canvas_drawimage.asp game.bufferCanvasCtx.drawImage( Función drawImage. spriteObject, Permite desplazarnos a un punto de una imagen, y posicionXdelPuntero, seleccionar una región a mostrar. posicionYdelPuntero, anchoSprite, altoSprite, posicionXenCanvas, positionYenCanvas, anchoEnCanvas, altoEnCanvas); }
  • 31. Sonidos var audio = document.createElement("audio"); //también sirve new Audio(); audio.oncanplaythrought=function(){ //sonidoCargado. audio.play(); } audio.src = “sound.mp3”;
  • 32. Video en HTML5 <video loop controls id="thevideo" width="320" height="240" preload="auto"> <source src="muirbeach.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' > <source src="muirbeach.webm"type='video/webm; codecs="vp8, vorbis"' > <source src="muirbeach.ogg" type='video/ogg; codecs="theora, vorbis"'> </video>
  • 33. Video con canal Alpha function processFrame() { buffer.drawImage(video, 0, 0); var image = buffer.getImageData(0, 0, width, height), imageData = image.data, alphaData = buffer.getImageData(0, height, width, height).data; for (var i = 3, len = imageData.length; i < len; i = i + 4) { imageData[i] = alphaData[i - 1]; } output.putImageData(image, 0, 0, 0, 0, width, height); } http://jakearchibald.com/scratch/alphavid/ ImageData Structure:
  • 34. Librerías 3D WebGL: three.js http://mrdoob.github.com/three.js/ Otras: WaveJS http://www.plainconcepts.com/wavejs
  • 35. PROJECT PROMETHEUS http://www.projectprometheus.com/trainingcenter/
  • 37. Preguntas / Dudas / Sugerencias #htmltour http://sh4wn.net/htmltour/demos_html5.zip