développement web - html5, css3, apis web

Post on 18-Dec-2014

335 Views

Category:

Education

5 Downloads

Preview:

Click to see full reader

DESCRIPTION

Support de cours de développement Web

TRANSCRIPT

Développement WebHTML5, CSS3, APIs W3C

A propos

Yoann Gotthilf, CTO d’une startup et freelance Web/Mobile

• développeur Web depuis 13 ans• développeur Fullstack JS depuis 1 ans• consultant sécurité pendant 6 ans • développeur Android depuis 6 ans

yoann.gotthilf at gmail.com • @ygotthilf

Références

• Site officiel du w3c : http://www.w3.org/• Site d’éducation non officiel : http://www.w3schools.com/• En français : http://www.alsacreations.com/

• Vérifier la compatibilité : http://caniuse.com/

• Editeurs en ligne : CodePen, JS Bin, JS Fiddle, ...

Les navigateurs

Histoire sans grand H

• 1990 : Tim Berners-Lee développe HTML (+ URL, HTTP)• 1994 : Fondation du W3C• 2000 : XHTML côtoie HTML 4.01• 2007 : W3C développe HTML5 (propulsé par WHATWG)• 2008 : Working Draft HTML5• 2010 : XHTML abondonné• 2012 : Candidate Recommendation HTML5

Syntaxe

• HTML est dérivé du SGML et non du XML<a href="#">Home</a><input type="text" value="John Doe" disabled><input type="text" value=John><input type="text" value="John Doe"><input type="text" value='John Doe'>

DTD

<!DOCTYPE html>

• Pour les validateurs W3C• Avant :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

Meta

<meta charset="utf-8">

• Pour le navigateur• Avant :

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

• Meta « keywords » obselète

Language

<html lang="en" > ... </html>

• pour les moteurs de recherche, navigateurs, synthétiseurs vocaux, ... • avant :

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

Script

<script src="javascript.js"></script>

• nouvel attribut : async• avant :

<script type="text/javascript" src="javascript.js"></script>

Elements supprimés

• <acronym>• <applet>• <basefont>• <big>• <center>• <dir>• <font>• <frame>• <frameset>• <noframes>• <strike>• <tt>

Structure

<header>

<footer>

<aside>

<section>

<nav>

Favorise :• Lisibilité• Accessibilité• Personnalisation• Optimisation indexation• Générateur auto table des

matières

<article>

<article>

<section>

Figure

<figure>

Content (image, video, ...)

Legend

Compatibilité IE 8/9

article, aside, details, figcaption, figure, footer, header, hgroup, nav, section, summary {display: block;

}

<!--[if lt IE 9]><script src="bower_components/html5shiv/dist/html5shiv.js"></script>

<![endif]-->

Forcer la CSS

Créer les élements HTML

Formulaire : types d’input• text• number• submit• File• range• search IE, FF, Opera

• email Safari

• url Safari

• color IE, Safari

• date, datetime, datetime-local, time, month, week IE, FF

• tel aucun support

Formulaire : attributs

• placeholder• autofocus• autocomplete="off" Opera

• disabled• size

Formulaire : validation

• required Safari, iOS, Android

• pattern Safari

• min, max, step FF

• novalidate Safari

Formulaire : compatibilité IE 8/9

A oublier...

Formulaire : vérifier la compatibilité

En natif :• Attribut :

var compatible = ‘placeholder' in document.createElement(‘input');

• Input Type :var el = document.createElement('input');el.setAttribute('type', 'datetime');var compatible = el.type !== 'text‘;

Avec Modernizr :• Attribut :

var compatible = Modernizr.input.placeholder ;

• Input Type :var compatible = Modernizr.inputtypes.datetime ;

Label 1/2<!-- #1 --><input type="checkbox"> <label>Nom 1</label>

<!-- #2 --><label><input type="checkbox"> Nom 2

</label>

<!-- #3 --><input type="checkbox" id="name"><label for="name">Nom 3</label>

Label 2/2<!-- Bad --><input type="checkbox"> <label>Nom 1</label>

<!-- Good --><label><input type="checkbox"> Nom 2

</label>

<!-- Good --><input type="checkbox" id="name"><label for="name">Nom 3</label>

Multimédia 1/2

<audio autoplay="autoplay" controls="controls"><source src="file.ogg" /><source src="file.mp3" /> <a>Download this file.</a>

</audio>

<video controls preload><source src="cohagenPhoneCall.ogv" type="video/ogg; codecs='vorbis, theora'" /><source src="cohagenPhoneCall.mp4" type="video/mp4; 'codecs='avc1.42E01E, mp4a.40.2'" /><p> Your browser is old</p>

</video>

Multimédia 2/2

• Sur un élement DOM <audio> ou <video> :• play()• pause()• load()• canPlayType()

• src• currentTime• Played

• timeupdate(fn)• seeking(fn)• ...

// ExemplemyVid=document.getElementById("video1");myVid.src="movie.ogg";myVid.play();

Drag and Drop (DnD) : Exemple 1/3

http://codepen.io/ygotthilf/pen/arCdF

<div id="todrag" class="col-25 left"><span draggable="true">Draggable n°1</span><span draggable="true">Draggable n°2</span><span draggable="true">Draggable n°3</span><span draggable="true">Draggable n°4</span>

</div>

<div class="col-50 left"><h2>Lâchez ici &darr;</h2><div id="mydropzone" ></div>

</div>

<div class="col-25 right"><div id="mylist" class="hidden"></div>

</div>

Drag and Drop (DnD) : Exemple 2/3

http://codepen.io/ygotthilf/pen/arCdF

<div id="todrag" class="col-25 left"><span draggable="true" ondragstart="dragStart(event)">Draggable n°1</span><span draggable="true" ondragstart="dragStart(event)">Draggable n°2</span><span draggable="true" ondragstart="dragStart(event)">Draggable n°3</span><span draggable="true" ondragstart="dragStart(event)">Draggable n°4</span>

</div>

<div class="col-50 left"><h2>Lâchez ici &darr;</h2><div id="mydropzone" ondragover="dragOver(event)" ondrop="drop(event)"></div>

</div>

<div class="col-25 right"><div id="mylist" class="hidden"></div>

</div>

var dndDone = false;

function dragStart (event){ event.target.style.background = "green";event.dataTransfer.setData("text/plain", event.target.innerText);dndDone = false;

}

function drop (event) {

var mylist = document.getElementById('mylist');mylist.classList.remove("hidden");

var span = document.createElement('span');span.innerHTML = event.dataTransfer.getData("text/plain");mylist.appendChild(span);

event.target.style.background = 'white';dndDone = true;

event.preventDefault();}

function dragOver (event){event.preventDefault();

}

[...]

Drag and Drop (DnD) : Exemple 3/3

http://codepen.io/ygotthilf/pen/arCdF

<div id="todrag" class="col-25 left"><span draggable="true" ondragstart="dragStart(event)" ondragend="dropEnd(event)">

Draggable n°1</span><span draggable="true" ondragstart="dragStart(event)" ondragend="dropEnd(event)">

Draggable n°2</span><span draggable="true" ondragstart="dragStart(event)" ondragend="dropEnd(event)">

Draggable n°3</span><span draggable="true" ondragstart="dragStart(event)" ondragend="dropEnd(event)">

Draggable n°4</span>

</div>

<div class="col-50 left"><h2>Lâchez ici &darr;</h2><div id="mydropzone" ondragenter="dragEnter(event)" ondragleave="dragLeave(event)"

ondragover="dragOver(event)" ondrop="drop(event)"></div></div>

<div class="col-25 right"> <div id="mylist" class="hidden"></div> </div>

[...]

function dropEnd (event) {if(dndDone) {

event.target.parentNode.removeChild(event.target);}else {

event.target.style.background = 'white'}

}

function dragEnter (event){event.target.style.background = "#CCCCCC";event.preventDefault();

}

function dragLeave (event){event.target.style.background = "white";event.preventDefault();

}

Drag and Drop (DnD) : Résumé

• Attribut draggable="true"• Evenements :

• dragstart• drag• dragend• dragenter• dragover• dragleave• drop

• event.dataTransfer• files (FileList)• dropEffect• effectAllowed• setData(type, data)• setDragImage(image, x, y)• clearData()

Canvas : présentation

Element HTML pour dessiner en JavaScript

• Bien supporté (sauf IE8)• Trois étapes à chaque fois :

1. <canvas id="mon_canvas" height="400px" width="400px"></canvas>2. var c = document.getElementById('mon_canvas');3. var ctx = c.getContext("2d");

• Librairies tierces :• Paper.js• Sketch.js• KineticJS• MelonJS• Processing.js• Fabric.js• ...

Canvas : exemplevar c = document.getElementById('mon_canvas');var ctx = c.getContext("2d");

// Gouvernailctx.fillStyle = "sienna";ctx.fillRect(275,250,25,70);

// Coque du bâteauctx.beginPath(); // Début d'un autre cheminctx.moveTo(50,250);ctx.lineTo(100,300);ctx.lineTo(250,300);ctx.lineTo(300,250);ctx.fillStyle = "peru";ctx.strokeStyle = "sienna"; // Définition du contourctx.lineWidth = 5; // Définition de la largeur de lignectx.fill(); // Application du remplissagectx.stroke(); // Application du contour

// Mâtctx.beginPath();ctx.moveTo(140,50);ctx.lineTo(140,250);ctx.lineWidth = 10;ctx.stroke();

// Voile du bateauctx.beginPath(); ctx.moveTo(150,80); ctx.lineTo(300,230); ctx.lineTo(150,230); ctx.closePath(); ctx.fillStyle = "lightblue"; ctx.fill();

// boule du mâtctx.beginPath();ctx.arc(140,50,10,0,Math.PI*2);ctx.fillStyle = "sienna";ctx.fill();

// Mervar gradient = ctx.createLinearGradient(0,280,0,400);gradient.addColorStop(0,"rgba(0,0,255,0.2)"); // Départgradient.addColorStop(1,"rgba(0,0,255,1)"); // Arrivéectx.fillStyle = gradient; // Affectation au remplissagectx.fillRect(0,280,400,120);

http://codepen.io/ygotthilf/pen/hKoDn

x

y

APIs Web

SVG

Afficher des dessins vectoriels dans le DOM

• Bien supporté (sauf IE8)• Librairies tierces :

• D3.js• Snag.svg• Processing.js• ...

• Exemple :<svg width="300" height="200"><polygon points="100,10 40,198 190,78 10,78 160,198"style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" />

</svg>

SVG vs CanvasSVG CanvasIndépendant de la résolutionManipulation d’événementsPerformance dégradé si dessin complexePas adapté au jeu

Dépendant de la résolutionPas de gestion des événementsPeu adapté au rendu de texteSauvegarde du dessin en .PNG ou .JPGAdapté au jeu

http://www.w3schools.com/html/html5_svg.asp

Géolocalisation : l’API 1/2

• Bien supporté (sauf IE8, forcément...)• Obtenir la localisation une seule fois :

• navigator.geolocation.getCurrentPosition (positionCb, errorCb, options)• Obtenir la localisation en continu :

• navigator.geolocation.watchPosition (positionCb, errorCb, options)• retourne l’id d’« abonnement »• s’annule via la méthode : clearWatch(id)

• Options possibles :• enableHighAccuracy• timeout• maximumAge

Géolocalisation : l’API 2/2

• Le callback de succès retourne un objet contenant :• timestamp • coordonnées :

• latitude• longitude• altitude• accuracy• altitudeAccuracy• heading• speed

• Le callback d’erreur retourne :• code : error.PERMISSION_DENIED, error.POSITION_UNAVAILABLE, error.TIMEOUT, error. UNKNOWN_ERROR• message

Géolocalisation : exemplevar x = document.getElementById("demo");

function getLocation() {if (navigator.geolocation) {

navigator.geolocation.getCurrentPosition(showPosition,function(error) {

x.innerHTML = "Geolocation failed : " + error.message + " (code " + error.code + ")";}, {

enableHighAccuracy: true,timeout: 10000

});} else {

x.innerHTML = "Geolocation is not supported by this browser.";}

}

function showPosition(position) {x.innerHTML = "Latitude: " + position.coords.latitude +"<br>Longitude: " + position.coords.longitude;

}

Web Storage : présentation

Stocker des données clés/valeurs dans le navigateur

• Compatible avec navigateur récent (et oui...)• Deux types de stockage :

• permanent : localStorage• temporaire (suppprimé à la fermeture de l’onglet) : sessionStorage

Web Storage : l’API

• Lire des données• getItem(clé)• Ou directement : localStorage.ma_clé• length• key(index)

• Ecrire des données • setItem(clé, valeur)• removeItem(clé)• clear()

if(typeof(Storage) !== "undefined") {// Code for localStorage/sessionStorage.localStorage.setItem("lastname", "Smith");var lastname = localStorage.getItem("lastname");

} else {// Sorry! No Web Storage support..

}

Web Storage : limitations

• Limité à au moins 5Mo• Protégé par nom de domaine (comme les cookies)• Stocke uniquement des chaînes de caractères :

• Caster la lecture d’un nombre• Utiliser JSON pour stocker/lire un objet

if (localStorage.clickcount) {localStorage.clickcount = Number(localStorage.clickcount) + 1;

} else {localStorage.clickcount = 1;

}

var user = {firstname : "Obi-Wan",lastname : "Kenoby"

};

var userJson = JSON.stringify(user);sessionStorage.setItem("user",userJson);

// ...

var userJson = sessionStorage.getItem("user");var user = JSON.parse(userJson);

Web Storage : déboguage

Dans la console de développement du navigateur

Chrome

Web Socket : présentation

Communication bidirectionnelle

• Incompatibe avec IE8/9 et navigrateur Android 4.3• web socket ≠ long polling (ajax)• Librairies tierces :

• Socket.IO• SignalR (ASP.NET)• Meteor (fullstack JS Framework)• Firebase (BaaS)• ...

Web Socket : l’API

Créer la websocket : • var ws= new WebSocket("ws://websocketUrl");

Intéragir avec les messages reçus :• ws.onopen = function(evt) { alert("Connection open ..."); }; • ws.onmessage = function(evt) { alert( "Received Message: " + evt.data); }; • ws.onclose = function(evt) { alert("Connection closed."); };• ws.onerror = function(evt) { alert("WebSocket error : " + e.data) };

Envoyer un message• ws.send(MyMessage);

Fermer la websocket :• ws.close();

Autres API

• Offline : rendre une application hors ligne (incompatibe IE8/9)

• Web Worker : lancer des tâches JavaScript isolées en parralèle (incompatibe IE8/9, Android 4.3)

• Server-Sent Events : mise à jour automatique d’une page grâce à des push server (incompatible IE)

• Web notification : notifier l’utilisateur en dehors du navigateur (uniquement FF, Chrome, Safari)

• Web RTC : Communication pair à pair (uniquement FF, Chome, Opéra)

• ...

Transformation

Effet pour changer la forme, taille, position d’un élément

• Propriété css : transform (-ms-, -webkit-, -moz-, -o- )

• Exemple :.content {

transform : rotate(45deg);}

http://codepen.io/ygotthilf/pen/asKnk

Transformations 2D

• translate(x,y) translateX, translateY

• rotate(deg)• scale(ratioX, ratioY) scaleX, scaleY

• skew(degX, degY) skewX, skexY

• matrix(n,n,n,n,n,n)

Transformation 3D

• translate3d(x,y,z)• rotate3d(x,y,z,angle)• scale3d(x,y,z)• matrix3d (n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n)• perspective(n)

<div class="container"><div class="content rotate3d">Hello world</div>

</div>

<div class="container perspective"><div class="content rotate3d">Hello world</div>

</div>

.perspective {perpective : 200px;-webkit-perspective : 200px;

}

.rotate3d {transform : rotateY(45deg);

}

http://codepen.io/ygotthilf/pen/asKnk

Transition

Effet appliqué à un changement de style d’un élement

• Propriété css globale : transition• 4 propriétés possibles :

• Propriété impactée• Délai• Durée• Timing function

.hide-on-hover {opacity : 1;transition : opacity 1s ease-in-out 500ms;

}

.hide-on-hover:hover {opacity : 0;

}

Transition : propriété impactée

Les priorités impactés par l’effet de transition

• Propriété : transition-property• Valeur par défaut : all• Possible d’ajouter plusieurs propriété, Exemple :

div {

transition-property: width, opacity;

}

Transition : délai et durée

• Délai : quand la transition démarre• Durée : combien de temps la transition dure

• Propriété délai : transition-delay • Propriété durée : transition-duration • Valeurs acceptées : seconde (s) ou milliseconde (ms)• Exemple :

div {

transition-delay: 2s;

transition-duration: 500ms;

}

Transition : timing function

La courbe de vitesse de l’effet

• Propriété : transition-timing-function • Valeurs acceptées :

• ease• linear• ease-in• ease-out• ease-int-out• cubic-bezier(n,n,n,n)

Timing function (source : Alsacréation)

Animation

Créer une animation sur un élément/* Chrome, Safari, Opera */@-webkit-keyframes disco {

0% {background: red;}25% {background: yellow;}50% {background: blue;}100% {background: green;}

}

/* Standard syntax */@keyframes disco {

0% {background: red;}25% {background: yellow;}50% {background: blue;}100% {background: green;}

}

.disco {-webkit-animation: disco 5s infinite; /* Chrome, Safari, Opera */animation: disco 5s infinite;

}

http://codepen.io/ygotthilf/pen/asKnk

Animation : @keyframes

Définir une animation

• Règle CSS : @keyframes• Proprités :

• from et to• pourcentage

@-webkit-keyframes myfirst {from {background: red;}to {background: yellow;}

}

/* Standard syntax */@keyframes myfirst {

from {background: red;}to {background: yellow;}

}

/* Chrome, Safari, Opera */@-webkit-keyframes myfirst {

0% {background: red;}25% {background: yellow;}50% {background: blue;}100% {background: green;}

}

/* Standard syntax */@keyframes myfirst {

0% {background: red;}25% {background: yellow;}50% {background: blue;}100% {background: green;}

}

Animation : comportement

• Prorité globale dans l’élement : animation• Proriétés

• animation-name (spécifié @keyframes)• animation-duration• animation-timing-function• animation-delay• animation-iteration-count (infinite ou nombre)• animation-direction (alternate, reverse, alternate-reverse, normal)• animation-play-state (paused ou running)

Media queries

Application une feuille de style en fonction du terminal

.bloc {background :black;}

@media screen and (min-width: 200px) and (max-width: 640px) {

.bloc {background :white;

}}

Media queries : type de terminal

Appliquer une CSS en fonction du type de terminal :• screen : Écrans• handheld : Périphériques mobiles ou de petite taille• print : Impression• speech :Synthèses vocales• braille : Plages braille• embossed :Imprimantes braille• projection :Projecteurs (ou présentations avec slides)• tty :Terminal/police à pas fixe• tv :Téléviseur• all :Tous les précédents

Media queries : propriétés du terminal

Les propriétés (à préfixer par min- ou max-) :• color : support de la couleur (bits/pixel)

• color-index : périphérique utilisant une table de couleurs indexées

• device-aspect-ratio : ratio du périphérique de sortie (par exemple 16/9)

• aspect-ratio : ratio de la zone d'affichage

• device-height : dimension en hauteur du périphérique

• device-width : dimension en largeur du périphérique

• grid : périphérique bitmap ou grille (ex : lcd)

• height : dimension en hauteur de la zone d'affichage

• monochrome : périphérique monochrome ou niveaux de gris (bits/pixel)

• orientation : orientation du périphérique (portait ou landscape)

• resolution :résolution du périphérique (en dpi, dppx, ou dpcm)

• scan : type de balayage des téléviseurs (progressive ou interlace)

• width : dimension en largeur de la zone d'affichage

top related