Animez vos pages HTML5

avec CSS3, SVG, Canvas et WebGL


Martin Gorner
République Tchèque, 25-26 Février 2013

Animate your HTML5 with CSS3, SVG, Canvas and WebGL Martin Gorner Czech Republic, February 25-26, 2013 Anime seu HTML5 com CSS3, SVG, Canvas e WebGL Martin Gorner [ Tradução: Átila Camurça ] Czech Republic, February 25-26, 2013

Transitions et Animations en CSS3

CSS3 Transitions and Animations Transições e Animações em CSS3
slide
slide with cubic BEZIER speed
slide with OPACITY
ROTATE
rotateX
rotate with modified ORIGIN
scaling ANIMATION with keyframe
skew ANIMATION with keyframe
3D rotate
--self-- --self-- --self-- --self-- --self-- --self-- --self-- --self-- --self-- --self-- slide com velocidade BÉZIER cúbica slide com opacidade ROTAÇÃO rotaçãoX rotação com origem modificada ANIMAÇÃO em escala com keyframe ANIMAÇÃO enviesada com keyframe rotação 3D

Transitions CSS3

left: 0px;
-webkit-transform:
        rotate(0deg);
-webkit-transition: 1s;
onclick
left: 500px;
-webkit-transform:
        rotate(360deg);
-webkit-transition: 1s;
CSS3 Transitions --self-- --self-- --self-- Transições em CSS3 --self-- --self-- --self--

Animations CSS3

.move {-webkit-animation: anim2 ease-in-out 3s infinite alternate; }
@-webkit-keyframes anim2
{
   from {left: 0px;   -webkit-transform: scale(1.0) rotate(0deg)   }
   50%  {left: 250px; -webkit-transform: scale(0.8) rotate(10deg)  }
   to   {left: 500px; -webkit-transform: scale(1.2) rotate(-20deg) }
}
CSS3 Animations --self-- --self-- Animações em CSS3 --self-- --self--

Transformations géométriques 2D

-webkit-transform:
rotate(90deg);
-webkit-transform:
scale(0.5);
-webkit-transform:
skew(20deg, 20deg);

liste complète des transformations 2D:
rotate, scale, skew, translate, matrix

2D geometric transforms Full list of 2D transform functions: --self-- Transformações geométricas 2D Lista completa de funções de transformação 2D: --self--

1. Transitions CSS3

-webkit-transition:
-webkit-transition-delay:
-webkit-transition-duration:
-webkit-transition-timing-function:
-webkit-transition-property:

2. Animations CSS3

-webkit-animation:
-webkit-animation-delay / duration / timing-function:
-webkit-animation-name: foo => @keyframes foo { from {} to {}}
-webkit-animation-direction:
-webkit-animation-fill-mode:
-webkit-animation-iteration-count:

3. Transformations 2D en CSS3

-webkit-transform: rotate / scale / skew / translate / matrix
1. CSS3 Transitions 2. CSS3 Animations 3. CSS3 Transforms in 2D 1. Transições em CSS3 2. Animações em CSS3 3. Transformações 2D em CSS3

Transformations 3D
en CSS3

3D transforms in CSS3 Transformações 3D em CSS3

Transformations géométriques 3D

translateX, Y, Z,     rotateX, Y, Z,     matrix3d

-webkit-transform: translateZ(150px)  /* first picture */
-webkit-transform: translateZ(-150px) /* second picture */
-webkit-transform: rotateY(360deg)    /* their container */ 
3D geometric transforms --self-- Transformações geométricas em 3D --self--

La perspective

Ce n'est pas ce qu'on veut: il manque la perspective!
Cliquer pour la rajouter.
-webkit-perspective: 1000px;
Perspective That is not what you wanted: there is no perspective! Click to add it. --self-- Perspectiva Não é o que você queria: Não há perspectiva! Clique para adicionar. --self--

La perspective

-webkit-perspective: f

Perspective --self-- --self-- Perspectiva --self-- --self--

La propriété transform-style

-webkit-transform-style: flat; /* default value */
The transform-style property --self-- --self-- --self-- A propriedade transform-style --self-- --self-- /* valor padrão */

La propriété transform-style

-webkit-transform-style:           preserve-3d;
The transform-style property --self-- --self-- --self-- A propriedade transform-style --self-- --self-- --self--

Bonne habitudes pour travailler en 3D

 SCENE {-webkit-perspective: 1000px}
OBJECT {-webkit-transform-style: preserve-3d   -webkit-transform: rotateX(30deg) ...;}
 FACE
{-webkit-transform: translateZ(150px);}
Best practices for working in 3D --self-- --self-- --self-- --self-- As melhores práticas para trabalhar em 3D --self-- --self-- --self-- --self--

Les CSS du cube 3D

.SCENE {
	-webkit-perspective: 1000px;
	width: 600px;
	height: 340px;
}
.OBJECT {
	-webkit-transform-style: preserve-3d;
	-webkit-transform: rotateX(0deg) rotateY(0deg) rotateZ(0deg);
	position: absolute;
	width: 100%;
	height: 100%;
}
.FACE {
	position: absolute;
	left: 165px;
	top: 15px;
}
.FACE.im1 { -webkit-transform: translateZ(150px); }
.FACE.im2 { -webkit-transform: translateZ(-150px); }
.FACE.im3 { -webkit-transform: translateX(150px) rotateY(90deg);}
.FACE.im4 { -webkit-transform: translateX(-150px) rotateY(-90deg);}
.FACE.im5 { -webkit-transform: translateY(150px) rotateX(90deg);}
.FACE.im6 { -webkit-transform: translateY(-150px) rotateX(-90deg);}
The CSS of the 3D cube --self-- --self-- --self-- O CSS do cubo 3D --self-- --self-- --self--

CSS 3D: animations, transition et transformation peuvent être combinées

CSS 3D: animations, transitions and transforms can be combined CSS 3D: animações, transições e transformações podem ser combinadas

Scalable Vector Graphics (SVG)

--self-- --self--

SVG: les primitives

<line x1 y1 x2 y2>
<rect x y width height>
<circle cx cy r>
<path d>
<image x y width height xlink:href>
<svg>
	<rect x="5" y="5" width="140" height="140" stroke="#000000"
	stroke-width="4" fill="#AAAAFF" opacity="1"/>
</svg>
SVG: primitives SVG: princípios

SVG: path - l'outil à tout faire

L - ligne

C - bézier cubique

Q - bézier quadratique

A - arc d'ellipse

M - Marqueur (nlle. pos. stylo)

z - pour fermer la courbe

Q C
<svg>
	<path d="M 30,240 Q 170,40 260,230" stroke="#F00" />
	<path d="M 30,240 C 70,90 210,150 260,230" stroke="#F00" />
</svg>

utilisez: INKSCAPE

SVG: path - the all-purpose tool L - line C - cubic bézier Q - quadratic bézier A - elliptic arc M - marker (new pen position) z - to close the path --self-- --self-- --self-- --self-- --self-- --self-- use: --self-- SVG: path - uma ferramenta para qualquer propósito L - linha C - bézier cúbica Q - bézier quadrática A - arco elíptico M - marker (new pen position) z - para fechar o path --self-- --self-- --self-- --self-- --self-- --self-- use: --self--

SVG: Transformations géométriques 2D

transform =
"translate(30, 0)"
transform =
"rotate(90, 100, 100)"
transform =
"scale(0.5)"

liste complète des transformations 2D:
translate, rotate, scale, skewX, skewY, matrix

<rect ... transform="translate(10,10) rotate(25) scale(2)">

SVG: geometric transforms in 2D full list of 2D transforms: --self-- --self-- SVG: transformações geométricas em 2D lista completa de transformações 2D: --self-- --self--

SVG+SMIL: animation sur un attribut

<circle cx="200" cy="205" r="80" >
	<animate dur="3s" attributeName="r" values="80; 150; 80"
	repeatCount="indefinite" />
</circle>
SVG+SMIL: animating an attribute SVG+SMIL: animação de um atributo

SVG+SMIL: l'attribut peut être le 'd' d'un tag path!

         
<path fill="#fff">
<animate attributeName="d" dur="2s" repeatCount="indefinite"
values="m 0,0  c  1,15 -13,45  -45,45  -32,0 -44,-28 -44,-44  z;
        m 0,0  c -4,15 -66,106 -98,106 -32,0   3,-89   9,-105 z" />
</path>
SVG+SMIL: the attribute can be the 'd' of a path tag! SVG+SMIL: o atributo pode ser o 'd' de uma tag path!

SVG+SMIL: animateTransform

<g> ... <!-- formes SVG groupées ici -->
  <animateTransform dur="3s" repeatCount="indefinite" additive="sum"
  attributeName="transform" type="translate" values="0,0; 200,-130" />
  <animateTransform dur="3s" repeatCount="indefinite" additive="sum"
  attributeName="transform" type="rotate" values="0; 20" />
</g>
--self-- SVG primitives group --self-- --self-- Grupos primitivos SVG --self--

SVG+SMIL: animateMotion

<g>
   ... <!-- formes SVG groupées ici -->
   <animateMotion dur="1s" repeatCount="indefinite"
   path="m 0,0 a 15,11 0 1 1 -30,0 15,11 0 1 1 30,0 z" />
</g>
--self-- SVG primitives group --self-- Grupos primitivos SVG --self--

SVG+SMIL: vitesse d'animation avec keySplines

1 temps 1 position 0 0
0.35 0 0.65 1
<animateTransform  calcMode="spline"
  dur="3s" attributeName="transform"
  type="rotate" repeatCount="indefinite"
  keySplines="0.35 0 0.65 1; 0.35 0 0.65 1"
  values="20,310,400; -20,310,400; 20,310,400" />
SVG+SMIL: animation speed with keySplines --self-- time --self-- --self-- --self-- --self-- --self-- --self-- --self-- --self-- --self-- --self-- SVG+SMIL: velocidade da animação com KeySplines --self-- tempo --self-- --self-- --self-- --self-- --self-- --self-- --self-- --self-- --self-- --self--

SVG: contrôle de l'animation en javascript

unpauseAnimations()

pauseAnimations()

setCurrentTime(0)

<g onclick="document.getElementById('svg_id').pauseAnimations()">...</g>
SVG: controlling the animation in javascript --self-- --self-- --self-- --self-- SVG: controlando a animação em javascript --self-- --self-- --self-- --self--

SVG: primitives (résumé)

<line>
<rect>
<circle>
<path>
<image>
<text>

SVG: tags d'animation (résumé)

<animate>
<animateTransform>
<animateMotion>

SVG: fonctions de contrôle de l'animation

pauseAnimations()
unpauseAnimations()
setCurrentTime(0)

SVG: primitives (summary) --self-- --self-- --self-- --self-- --self-- --self-- SVG: animation tags (summary) --self-- --self-- --self-- SVG: animation control --self-- --self-- --self-- SVG: princípios (sumário) --self-- --self-- --self-- --self-- --self-- --self-- SVG: tags de animação (sumário) --self-- --self-- --self-- SVG: controle da animação --self-- --self-- --self--

Les 4 techniques d'animation en HTML5

CSS3déclaratifobjets HTML uniquement, aucun contrôle de trajectoire
SVG + SMILdéclaratifcourbes, trajectoires courbes mais préprogrammées
Canvas + Javascriptprogrammatiqueboucle d'animation avec modèle et interactions libres, 2D uniquement
WebGL + Three.jsprogram-
matique
full 3D
4 HTML5 animation techniques --self-- declarative only HTML objects, no control over trajectory --self-- declarative curves, curved trajectories, but only preprogrammed ones --self-- programmatic animation loop with interactive world model, 2D only --self-- program- matic full 3D 4 técnicas de animação em HTML5 --self-- declarativa somente objetos HTML, sem controle sobre a trajetória --self-- declarativa curvas, trajetórias em curva, mas já preprogramadas --self-- programática loop de animação interativo, somente 2D --self-- progra- mática totalmente 3D

Canvas

moteur physique: box2dweb.js

--self-- physics engine: --self-- --self-- engine para física: --self--

Canvas: mise ne place

HTML:
<canvas id     = "my-canvas"
        width  = "400"
        height = "400"
        style  = "width: 400px;
                  height: 400px;">
</canvas>
Javascript:
var canvasElement = document.getElementById("my-canvas");

var ctx = canvasElement.getContext("2d");
  
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
Canvas: setting it all up --self-- --self-- --self-- Canvas: configurando tudo --self-- --self-- --self--

Canvas: primitives de dessin

ctx.strokeStyle = "red"; // CSS color
ctx.fillStyle = "blue"; // CSS color
ctx.lineWidth = 5; // pixels
ctx.globalAlpha = 0.5;
ctx.beginPath(); ctx.closePath();
ctx.moveTo(x, y);
ctx.lineTo(x, y);
ctx.rect(x1, y1, w, h);
ctx.arc(x, y, r, bAng, eAng, dir);
ctx.bezierCurveTo(vx, vy, wx, wy, x, y);
ctx.stroke();
ctx.fill();
Canvas: drawing primitives Canvas: princípios de desenho

Canvas: afficher des images

BITMAP
var img = new Image();
img.onload = function()
{
   ctx.drawImage(img, x,y, w,h);
};
img.src = "myimage.png";
SVG
var data = "<svg>...</svg>";
var svg = new Blob([data],{type:"image/svg+xml"});
var DOMURL = self.URL || self.webkitURL;
var url = DOMURL.createObjectURL(svg);
var img = new Image();
img.onload = function()
{ ctx.drawImage(img, x, y, w, h); };
img.src = url;
! Chrome uniq.
! SVG inline uniq.
! pas d'anim SMIL
Canvas: displaying pictures --self-- --self-- --self-- --self-- ! Chrome only ! inline SVG only ! no SMIL anim. Canvas: mostrando figuras --self-- --self-- --self-- --self-- ! somente Chrome ! somente inline SVG ! sem anim. SMIL

Canvas: transformations géométriques

ctx.translate(x, y);
// dessiner ici
Translation
ctx.rotate(rads);
// dessiner ici
Rotation
ctx.scale(sx, sy);
// dessiner ici
Zoom
utiliser ctx.save() et ctx.restore() pour gérer l'état du contexte Canvas: geometric transforms --self-- draw here Translation --self-- draw here Rotation --self-- draw here Scale use  --self-- and  --self-- to handle drawing ctx. state Canvas: transformações geométricas --self-- desenhe aqui Mudar de posição --self-- desenhe aqui Rotação --self-- desenhe aqui Aumentar/Diminuir use  --self-- e  --self-- para manipular o estado do ctx.

Canvas: composer les transformations géométriques

1. Le Dessin
2. Centrer
3. Zoom
4. Rotation
5. Position
Etapes à rejouer en sens inverse:
/*5*/ ctx.translate(x, y);
/*4*/ ctx.rotate(4.5);
/*3*/ ctx.scale(0.6, 0.6);
/*2*/ ctx.translate(-width/2, -height/2);
/*1*/ ctx.beginPath(); // dessiner ici
Canvas: composing geometric transforms 1. The drawing 2. Center 3. Scale 4. Rotate 5. Position Replay the transforms in reverse order: draw from here Canvas: compondo transformações geométricas 1. O desenho 2. Centro 3. Escala 4. Rotação 5. Posição Repita as transformações em ordem inversa: desenhe deste ponto

Canvas: les boucles d'animation

function runAnimation()
{
    world.Draw(context); // votre code de dessin
    webkitRequestAnimationFrame(runAnimation);
}
function runWorld()
{
    world.Step(1000/60); // votre code de simulation
    setTimeout(runWorld, 1000/60);
}
Le navigateur optimise les appels à requestAnimationFrame
Canvas: animation loops your drawing code --self-- your simulation code The browser optimizes requestAnimationFrame calls Canvas: loops de animação seu código do desenho --self-- seu código de simulação O navegador otimiza as chamadas requestAnimationFrame

WebGL

  +   THREE.js

PRETS ?
--self-- --self-- READY ? --self-- --self-- PRONTOS?

THREE.js: camera, lumières, action !

Créer un moteur de rendu WebGL
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(width, height);
renderer.setClearColorHex(0x000000, 0); // color, transparency
L'ajouter au document
document.ouvousvoulez.appendChild(renderer.domElement);
Créer une caméra
// THREE.PerspectiveCamera( FOV, viewAspectRatio, zNear, zFar );
var camera = new THREE.PerspectiveCamera(35, width/height, 1, 10000);
camera.position.z = 300;
THREE.js: camera, lights, action ! Create a WebGL renderer Add it to the document whereeveryouwant Create a camera THREE.js: luz, câmera, ação! Cria uma renderizador WebGL Adiciona-o ao documento whereeveryouwant Cria uma câmera
Une lumière
var light = new THREE.DirectionalLight(0xffffff, 1); //color, intens.
light.position.set(1, 1, 0.3); // direction
Quelque chose à afficher
var texture = THREE.ImageUtils.loadTexture('Fernando Togni.jpg');
var cube = new THREE.Mesh(
               new THREE.CubeGeometry(100, 100, 100),
               new THREE.MeshLambertMaterial({map: texture}) );
Une scène avec tout ça
var scene = new THREE.Scene();
scene.add(cube);
scene.add(light);
Let there be light Something to display A scene with all of this Permita que haja luz Algo para mostrar Uma cena com tudo isso

... et action !

renderer.render(scene, camera);
... and action ! --self-- ... e ação! --self--

La boucle d'animation

function runAnimation(t)
{
    // animer les objets en fonction du temps
    cube.rotation.y =  t/1000;
    cube.position.x = ...
    
    renderer.render(scene, camera); // afficher
    requestAnimationFrame(runAnimation); // boucler
}
The animation loop animate your objects depending on time --self-- display --self-- and loop O loop de animação anima seus objetos dependendo do tempo --self-- mostrar --self-- e loop

THREE.js: charger un modèle

Format ouvert de modèles 3D: COLLADA (.dae)
var loader = new THREE.ColladaLoader();

loader.load("Android.dae", function(collada)
           {
               var model = collada.scene;
               model.position = ...; // x, y, z
               model.rotation = ...; // x, y, z
               scene.add(model);
           },
               function progress(p) {} );

utilisez: SKETCHUP

THREE.js: load a model Open 3D model data format: COLLADA (.dae) use --self-- THREE.js: carregue um modelo Abra um modelo 3D no formato: COLLADA (.dae) use --self--

WebGL + THREE.js: résumé

renderer = new THREE.WebGLRenderer(...)
camera   = new THREE.PerspectiveCamera(...)
light    = new THREE.DirectionalLight(...)
           new THREE.ColladaLoader().load(modelUrl, finishedCallback)
scene    = new THREE.Scene()
scene.add(...); // lights, models, ...

window.requestAnimationFrame(animate);
function animate(t)
{
     // animation: modifier la scène en fonction du temps t ici
     renderer.render(scene, camera);
     window.requestAnimationFrame(animate);
}
WebGL+ THREE.js: summary // animation: change the scene here depending on time t WebGL+ THREE.js: sumário // animação: mude a cena aqui dependendo to tempo t

Les 4 techniques d'animation en HTML5

CSS3déclaratifobjets HTML uniquement, aucun contrôle de trajectoire
SVG + SMILdéclaratifcourbes, trajectoires courbes mais préprogrammées
Canvas + Javascriptprogrammatiqueboucle d'animation avec modèle et interactions libres, 2D uniquement
WebGL + Three.jsprogram-
matique
full 3D
4 HTML5 animation techniques --self-- declarative only HTML objects, no control over trajectory --self-- declarative curves, curved trajectories, but only preprogrammed ones --self-- programmatic animation loop with interactive world model, 2D only --self-- program- matic full 3D 4 técnicas de animação em HTML5 --self-- declarativa somente objetos HTML, sem controle sobre a trajetória --self-- declarativa curvas, trajetórias em curva, mas já preprogramadas --self-- programática loop de animação interativo, somente 2D --self-- progra- mática totalmente 3D

Show time !

--self-- --self-- --self-- Particles and GPGPU --self-- --self-- --self-- --self-- --self-- --self-- --self-- --self-- Materials, bump mapping Environment map, bump map, shadows --self-- --self-- --self-- (with Google Maps and Earth) Hora do show! --self-- --self-- Partículas e GPGPU --self-- --self-- --self-- --self-- --self-- --self-- --self-- --self-- Materiais, bump mapping Mapa de ambiente, bump map, sombras --self-- --self-- --self-- (com Google Maps e Earth)

chrome

--self-- --self--

Contact:
Martin Gorner, Relations Développeurs, Google
Google+: gplus.to/martin.gorner

Cette présentation est en ligne:
http://animateyourhtml5.appspot.com

Tutoriel WebGL et THREE.JS
http://fhtr.org/BasicsOfThreeJS par Ilmari Heikkinen

Plus d'infos:
http://html5rocks.com

Contact info: --self-- , Developer Relations, Google --self-- --self-- This presentation is available online: --self-- --self-- --self-- WebGL and THREE.js tutorial: --self-- --self-- by Ilmari Heikkinen And much more on: --self-- --self-- --self-- Contato: --self-- , Developer Relations, Google --self-- --self-- Esta apresentação está disponível online: --self-- --self-- --self-- Tutorial WebGL e THREE.js: --self-- --self-- por Ilmari Heikkinen E muito mais em: --self-- --self-- --self--