SlideShare uma empresa Scribd logo
1 de 46
Baixar para ler offline
Paradigmas Emergentes para a WEB




HTML 5

ANTÓNIO MARQUES, 2012

amarques@utad.pt

Gabinete F1.21 Eng1
Índice resumido

1. Desenhar com o elemento CANVAS
2. Drag and Drop
3. Controlos de Formulários
4. Edição Inline
5. Trabalhar com o Histórico do Browser
6. Troca de Mensagens entre Janelas
7. Uso de Vídeo e Áudio
8. Armazenamento de dados
1 - O elemento CANVAS
O elemento CANVAS é usado para desenhar gráficos.
É criado com a seguinte instrução:

<canvas height=“xxx” width =“yyy”>
</canvas>

Para desenhar no canvas usa-se JavaScript.

Pode-se desenhar linhas, arcos, formas complexas,
texto, imagens, etc.

O W3C definiu uma API (Application Programming
Interface), onde definiu o nome das funções e como
devem ser usadas.
http://www.w3.org/TR/2dcontext/
CANVAS API
A API define atributos dos elementos e as funções em JavaScript.
É necessário atribuir alguns atributos antes de usar as funções de desenho.
Exemplo:

Canvas1.fillStyle = xxx;
Canvas1.fillRectangle(x,y,dx,dy);

Lista de atributos e funções:
  Styling
     • attribute any strokeStyle; // (default black)
     • attribute any fillStyle; // (default black)

 Line Styles
    • attribute DOMString lineCap; // “butt”, “round”, “square” (default “butt”)
    • attribute DOMString lineJoin; // “miter”, “round”, “bevel” ) (default “miter”)
    • attribute float lineWidth; // (default 1)
    • attribute float miterLimit; // (default 10)
Shadows
    • attribute float shadowBlur; // (default 0)
    • attribute DOMString shadowColor; // (default transparent black)
    • attribute float shadowOffsetX; // (default 0)
    • attribute float shadowOffsetY; // (default 0)
Rectangles
    • clearRect(float x, float y, float w, float h);
    • fillRect(float x, float y, float w, float h);
    • strokeRect(float x, float y, float w, float h);
Complex Shapes
    • arc(float x, float y, float radius, float startAngle, float endAngle, boolean anticlockwise);
    • arcTo(float x1, float y1, float x2, float y2, float radius);
    • beginPath();
    • bezierCurveTo(float cp1x, float cp1y, float cp2x, float cp2y, float x, float y);
    • clip();
    • closePath();
    • fill();
    • lineTo(float x, float y);
    • moveTo(float x, float y);
    • quadraticCurveTo(float cpx, float cpy, float x, float y);
    • rect(float x, float y, float w, float h);
    • stroke();
    • boolean isPointInPath(float x, float y);
Text
    • attribute DOMString font; // (default 10px sans-serif)
    • attribute DOMString textAlign; // “start”, “end”, “left”, “right”, “center” (default: “start”)
    • attribute DOMString textBaseline; // “top”, “hanging”, “middle”,
           “alphabetic”, “ideographic”, “bottom” (default: “alphabetic”)
    • fillText(DOMString text, float x, float y, optional float maxWidth);
    • TextMetrics measureText(DOMString text);
    • strokeText(DOMString text, float x, float y, optional float maxWidth);
Images
    • drawImage(HTMLImageElement image, float dx, float dy, optional float dw, float dh);
    • drawImage(HTMLImageElement image, float sx, float sy, float sw,
                               float sh, float dx, float dy, float dw, float dh);
    • drawImage(HTMLCanvasElement image, float dx, float dy, optional float dw, float dh);
    • drawImage(HTMLCanvasElement image, float sx, float sy, float sw,
                                float sh, float dx, float dy, float dw, float dh);
    • drawImage(HTMLVideoElement image, float dx, float dy, optional float dw, float dh);
    • drawImage(HTMLVideoElement image, float sx, float sy, float sw,
                               float sh, float dx, float dy, float dw, float dh);
Transformations
    • rotate(float angle);
    • scale(float x, float y);
    • translate(float x, float y);
Exemplo de uso de CANVAS
  1. Criar um ficheiro canvas.html com um editor de texto. *
  2. Escrever o seguinte código, para criar o Canvas e fazer o setup do JavaScript:
        <!DOCTYPE html>
        <html>
          <head>
            <title>
              Exemplo de Canvas
            </title>
                     http://www.activestate.com/komodo-
            <script type="text/javascript">
            functionedit/downloads
                      loader()
            {
            }
            </script>
          </head>
        <body onload="loader()">
          <h1>Exemplo de Canvas</h1>
          <canvas id="canvas" height="500" width="600">
          </canvas>
        </body>
        </html>

•http://www.activestate.com/komodo-edit/downloads
Editor gratuito, com versões para Mac, Linux e Windows. Com Intellisense para HTML 5
3. Adicionar o código JavaScript para criar um objecto do elemento Canvas

       <script type="text/javascript">
      function loader()
         {
           var canvas = document.getElementById('canvas');
           var canvas1= canvas.getContext('2d');
         }
      </script>




4. Gravar o ficheiro no formato de texto.
5. Experimentar em vários Browsers.
Desenhar Rectângulos
     6. Escrever o seguinte código para criar 3 rectângulos de diferentes cores
function loader()
{
  var canvas = document.getElementById('canvas');
  var canvas1= canvas.getContext('2d');

    //Rectângulos
    canvas1.fillStyle="rgba(0,0,200,1)"; //Côr Azul
    canvas1.fillRect(30,30,75,70);

    canvas1.fillStyle="rgb(200,200,0)";
    canvas1.fillRect(70,50,55,70);

    canvas1.fillStyle = "rgba(200, 0, 0, 1)";
    canvas1.fillRect(90, 50, 75, 50);
}




     7. Gravar e experimentar
Desenhar Linhas
1. Abrir o ficheiro e acrescentar o seguinte código:
 function loader()
 {
 //Desenhar Triângulos
 canvas1.beginPath();
 canvas1.strokeStyle = "rgba(200, 0, 0, 0.5)";
 canvas1.moveTo(110, 205);
 canvas1.lineTo(110, 125);
 canvas1.lineTo(30, 205);
 canvas1.closePath();
 canvas1.stroke();

 canvas1.beginPath();
 canvas1.moveTo(100, 205);
 canvas1.lineTo(100, 125);
 canvas1.lineTo(20, 205);
 canvas1.closePath();
 canvas1.stroke();

 canvas1.beginPath();
 canvas1.moveTo(90, 205);
 canvas1.lineTo(90, 125);
 canvas1.lineTo(10, 205);
 canvas1.closePath();
 canvas1.stroke();
 }
Desenhar Linhas Preenchidas
1. Acrescentar o seguinte código:
  function loader()
    {
             //Filled triangle
      canvas1.fillStyle = "rgba(0, 200, 0, 0.5)";
      canvas1.beginPath();
      canvas1.moveTo(225, 25);
      canvas1.lineTo(305, 25);
      canvas1.lineTo(225, 105);
      canvas1.closePath();
      canvas1.fill();
      }
Desenhar Curvas de Bezier

function loader()
{
     // Heart
canvas1.fillStyle = "rgba(200, 0, 0, 0.5)";
canvas1.beginPath();
canvas1.moveTo(75, 250);
canvas1.bezierCurveTo(75, 247, 70, 235, 50, 235);
canvas1.bezierCurveTo(20, 235, 20, 272.5, 20, 272);
canvas1.bezierCurveTo(20, 290, 40, 312, 75, 330);
canvas1.bezierCurveTo(110, 312, 130, 290, 130, 272);
canvas1.bezierCurveTo(130,272.5, 130, 235, 100, 235);
canvas1.bezierCurveTo(85, 235, 75, 247, 75, 250);
canvas1.closePath();
canvas1.fill();
}
Desenhar Curvas Quadráticas

function loader()
{
          //Quadratic curves
  canvas1.strokeStyle = "rgba(0, 0, 0, 1)";
  canvas1.beginPath();
  canvas1.moveTo(275, 125);
  canvas1.quadraticCurveTo(225, 125, 225, 162);
  canvas1.quadraticCurveTo(260, 200, 265, 200);
  canvas1.quadraticCurveTo(325, 200, 325, 162);
  canvas1.quadraticCurveTo(325, 125, 275, 125);
  canvas1.closePath();
  canvas1.stroke();
  }
Desenhar Arcos

function loader()
{
         // Arcs
canvas1.beginPath();
canvas1.arc(275,275, 50, 0, Math.PI * 2, true);
canvas1.moveTo(310, 275);
canvas1.arc(275, 275, 35, 0, 0.75 * Math.PI,
                                  false);
canvas1.moveTo(300, 255);
canvas1.arc(265, 255, 35, 0, 0.5 * Math.PI,
                                  false);
canvas1.moveTo(280, 255);
canvas1.arc(245, 255, 35, 0, 0.2 * Math.PI,
                                  false);
canvas1.closePath();
canvas1.stroke();
}
Desenhar Texto


function loader()
{
         //Texto
canvas1.font = 'italic 40px sans-serif';
canvas1.strokeText("Olá!", 50, 400);
}
2 - Drag and Drop
Com o suporte de Drag and Drop, podemos deslocar elementos e texto pelo
browser, com o uso do rato ou outro dispositivo apontador.
Como exemplo, podemos deslocar itens para um cesto de compras;
configurar a nossa homepage; etc.

O Drag and Drop é suportado com a criação de novos atributos dos
elementos, como o atributo draggable que colocado a true permite a esse
elemento ser deslocado. No entanto todo o processamento é feito em
JavaScript.

A API para trabalhar com o Drag and Drop está definida em:

http://dev.w3.org/html5/spec/dnd.html
Drag and Drop negado   Drag and Drop permitido
Criar um ficheiro, dragandrop.html, e escrever este código
<!DOCTYPE HTML>                               </head>
<html>                                            <body>
    <head>                                            <h1>Drag and Drop Example</h1>
        <title>                                       <div id="target1">
        Drag and Drop Example                             <div id="draggable1">1
        </title>                                          </div>
                                                          <div id="draggable2">2
    <style type="text/css">                               </div>
    #target1, #target2, #target3                          <div id="draggable3">3
    {                                                     </div>
    float:left; width:250px; height:250px;            </div>
    padding:10px; margin:10px;                        <div id="target2">
    }                                                 </div>
    #draggable1, #draggable2, #draggable3             <div id="target3">
    {                                                 </div>
      width:75px; height:70px; padding:5px;       </body>
      margin:5px;                             </html>
    }
    #target1 {background-color:cyan;}
    #target2 {background-color:blue;}
    #target3 {background-color:cyan;}
    #draggable1 {background-color:
orange;}
      #draggable2 {background-color:
orange;}
      #draggable3 {background-color:
orange;}
    </style>
Colocar o atributo draggable nos elementos que se querem mover:
</head>
    <body>
     <h1>Drag and Drop Example</h1>
    <div id="target1">
      <div id="draggable1” draggable="true" >1
      </div>
      <div id="draggable2” draggable="true" >2
      </div>
      <div id="draggable3” draggable="true" >3
      </div>
    </div>
      <div id="target2">
      </div>
      <div id="target3">
      </div>
    </body>
</html>




Experimentar em vários browsers
Colocar os atributos nos elementos de destino:

</head>                                       ondragenter – evento que ocorre
  <body>
  <h1>Drag and Drop Example</h1>              quando um elemento que está a ser
   <div id="target1“                          arrastado entra na área do elemento
      ondragenter="return enter(event)"
      ondragover="return over(event, this)"
      ondrop="return drop(event)" >           ondragover - evento que ocorre quando
   </div>                                     o elemento que está a ser arrastado está
   <div id="target2“
      ondragenter="return enter(event)"       sobre o elemento
      ondragover="return over(event,this)"
      ondrop="return drop(event)" >
                                              ondrop - evento que ocorre quando o
    </div>
    <div id="target3“                         elemento é largado em cima do
      ondragenter="return enter(event)"       elemento
      ondragover="return over(event,this)"
      ondrop="return drop(event)" >
     </div>
    </body>
</html>
Colocar os atributos nos elementos a arrastar:
.
.
<div id="draggable1" draggable="true"              ondragstart – evento que ocorre
    ondragstart="return start(event)"              quando o elemento draggable,
    ondragend="return end(event)">1
</div>
                                                   começa a ser movimentado
<div id="draggable2" draggable="true“
    ondragstart="return start(event)“              ondragend – evento que ocorre
    ondragend="return end(event)">2                quando se larga o elemento
</div>
<div id="draggable3" draggable="true“
    ondragstart="return start(event)“
    ondragend="return end(event)">3
</div>
.
.
Implementar a função start()
.
.
<script type="text/javascript">
    function start(e)
    {
      e.dataTransfer.effectedAllowed=“move”;
      e.dataTransfer.setData("Data",e.target.getAttribute('id'));
      e.dataTransfer.setDragImage(e.target, 0, 0);
      return true;
      }
</script>
</head>
  .
.




  No parâmetro e define-se os dados que vão ser transmitidos, e o modo.
  Neste caso vai executar um move, coloca, com setData, o id do elemento que
  está a ser arrastado.
  A função setDragImage, define a imagem a ser transferida, neste caso o
  elemento a ser arrastado, e um offset, neste caso 0,0
Implementar a função enter()
.
.
<script type="text/javascript">
function enter(e)
        {
            return true;
        }
        </script>
    </head>
  .
.
Implementar a função over()
.
.
<script type="text/javascript">
  function over(e, element)
  {
    var iddraggable = e.dataTransfer.getData("Data");
    var id = element.getAttribute('id');
    if(id==‘target1’)
         return false;
    if((id=='target2') && iddraggable == 'draggable3')
         return false;
    else if(id=='target3' && (iddraggable == 'draggable1' ||
                      iddraggable == 'draggable2'))
           return false;
           else
              return true;
         }
         </script>
     </head>
  .
.
Implementar a função drop()
<script type="text/javascript">
 function drop(e)
 {
   var iddraggable=e.dataTransfer.getData("Data");

   e.target.appendChild(document.getElementById(iddraggable));
   e.stopPropagation();
   return false;
  }
</script>
</head>




  Implementar a função end()
<script type="text/javascript">
 function end(e)
  {
    e.dataTransfer.clearData("Data");
    return true;
  }
 </script>
    </head>
3 - Controlos de Formulários
      O HTML 5 introduziu novos tipos de controlos
      para a introdução de dados num formulário.

      Estes controlos estendem o controlo <input>,
      acrescentando outro tipos aos já existentes (text,
      radio,etc.).




http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html
Os controlos de formulário são criados com o elemento <input>, definindo
no atributo type, qual o tipo de controlo:
Criar um ficheiro webform.html, e escrever este código
<!DOCTYPE html>
<html>
                  <head>
          <title>
                Web Form Example
          </title>
                 </head>
                <body>
          <h1>Web Form Example</h1>
          <form method=“post” action=“webforms.php”>
                <table border=“1” cellpadding=“5”>
             .
             .
             .
               </table>
               <input type=“submit” value=“Submit”>
          </form>
           </body>
</html>
Introduzir o controlo default
               <table border=“1” cellpadding=“5”>
              <tr>
                 <td>Deafult</td>
                 <td><input name=“name” placeholder=“Introduza o
login”
                   required=true autofocus>
                 </td>
              </tr>
          .
              </table>
              <input type=“submit” value=“Submit”>
          </form>
           </body>
</html>

Introduzir o controlo Url
               <table border=“1” cellpadding=“5”>
          .
                </tr>
               <tr>
                  <td>URL</td><td><input name=“url”
          type=“url”></td>
              </tr>
              </table>
              <input type=“submit” value=“Submit”>
          </form>
           </body>
</html>
Introduzir o controlo email
         <table border=“1” cellpadding=“5”>
              .
           <tr>
              <td>Email</td>
              <td><input name=“email” type=“email”></td>
           </tr>
         .
         </table>
              <input type=“submit” value=“Submit”>
         </form>
      </body>
</html>


 Introduzir os controlos Range e number
         <table border=“1” cellpadding=“5”>
         .
           <tr>
             <td>Range</td><td><input name=“range” type=“range”
                 min=“0” max=“100” step=“5” value=“40”></td>
           </tr>
           <tr>
             <td>Number</td><td><input name=“number” type=“number”
         min=“0” max=“100” step=“5” value=“40”></td>
           </tr>
        </table>
Introduzir os controlos de Data e Hora
         <table border=“1” cellpadding=“5”>
         <tr>
          <td>Date</td><td><input name=“date” type=“date”></td>
         </tr>
         <tr>
            <td>Week</td><td><input name=“week” type=“week”></td>
         </tr>
         <tr>
              <td>Month</td><td><input name=“month” type=“month”></td>
         </tr>
         <tr>
              <td>Time</td><td><input name=“time” type=“time”></td>
         </tr>
         <tr>
            <td>Datetime</td><td><input name=“datetime”
type=“datetime”></td>
         </tr>
         <tr>
            <td>Local Datetime</td><td><input name=“datetimelocal”
                   type=“datetime-local”></td>
         </tr>
      </table>
Introduzir o controlo Color
        <table border=“1” cellpadding=“5”>
        .
           <tr>
             <td>Color</td><td><input name=“color” type=“color”></td>
              </tr>
           </table>



 Introduzir o controlo Search

            <table border=“1” cellpadding=“5”>
        .
              <tr>
                 <td>Search Query</td><td><input name=“query”
                            type=“query”></td>
              </tr>
            </table>
Criar o ficheiro webforms.php, que vai atender à submissão do formulário

<html>
    <head>
        <title>
             Reading data from datetime controls
        </title>
    </head>
    <body>
        <h1>
             Lêr os dados do contolo Datetime
        </h1>
             Introduziu:
        <?php
             echo $_REQUEST['datetime'];
        ?>
    </body>
</html>
4 – Edição Inline
HTML5 especifica que se pode fazer elementos
editáveis, ou seja, permitir que o utilizador edite o
seu conteúdo.
Isso não quer dizer que estamos a falar de campos
de texto, mas sim qualquer tipo de elementos,
tais como o elemento <div>.
Além disso, podemos fazer um documento inteiro
editável, incluindo elemento <iframe>. Também
se pode fazer a verificação ortográfica do texto
introduzido.
Para usar a edição usa-se três atributos:
• contenteditable – torna um elemento HTML editável
• designmode – torna todo o documento editável
• spellcheck – activa o corrector ortográfico


Exemplo do uso do atribbuto contenteditable

Criar o ficheiro editdiv.html
<!DOCTYPE html>
<html>
    <head>
        <title>
        Editable &lt;div&gt; Element
        </title>
   </head>
   <body>
        <h1>Editable &lt;div&gt; Element</h1>
         .
         .
   </body>
</html>
Introduzir o seguinte div com o atributo contenteditable a true
<body>
    <h1>Editable &lt;div&gt; Element</h1>
    <br> .
     <div id="div" style='border:solid black; height: 300px; width: 400px'
        contenteditable="true“>
     </div>
   </body>
</html>



  Introduzir o código para criar o botão Negrito e executar o comando ‘bold’

<body>
   <h1>Editable &lt;div&gt; Element</h1>
   <div>
       <input type="button" value=“Negrito"
                onclick="document.execCommand('bold', false, null);">
    </div>
          .
    <br>
    <div id="div" style='border:solid black; height: 300px; width: 400px'
         contenteditable="true">
     </div>
   </body>
Introduzir os restantes botões:

<body>
         <h1>Editable &lt;div&gt; Element</h1>
        <div>
          <input type="button" value=“Negrito"
                onclick="document.execCommand('bold', false, null);">
          <input type="button" value="Itálico"
                onclick="document.execCommand('italic', false, null);">
         <input type="button" value="Sublinhado"
                onclick="document.execCommand('underline', false, null);">
         <input type="button" value="Criar Link"
                onclick="createLink();">
         <input type="button" value="Mostar Source"
                onclick="showSource();">
       </div>
     <br>
       <div id="div" style='border:solid black; height: 300px; width:
400px'
         contenteditable="true">
     </div>
   </body>
Introduzir as funções de JavaScript para os botões “Criar Link” e “Mostrar Source”

</title>
       <script type="text/javascript">
       function showSource()
       {
           var content = document.getElementById("div").innerHTML;
           content.replace(/</g, '&lt;');
           content.replace(/>/g, '&gt;');
           alert(content);
       }
       function createLink()
       {
           var url = prompt("Enter URL:", "http://");
           if (url)
           document.execCommand("createlink", false, url);
       }
       </script>
5 – Trabalhar com o Histórico do Browser
 O HTML5 permite o controle sobre o histórico do
 navegador. O objeto History, permite avançar e
 retroceder, de página para página no navegador,
 o que significa que se pode usá-lo por exemplo,
 para voltar três páginas atrás.
 Também se pode armazenar dados num objeto
 de estado no history. Ou seja, pode-se adicionar
 dados no objeto de estado e, em seguida, para
 armazená-lo com a página atual. Os dados
 guardados n o objeto de estado, pode ser
 recuperado, o que permite passar dados de uma
 página para outra.
O object history faz parte do objecto window, assim é referido window.history.

Atributos e funções definidas na API:

• window.history.length -> número de páginas no history
• window.history.back() -> vai para a página anterior
• window.history.forward() -> vai para a página seguinte
• window.history.go([delta]) -> vai para delta páginas para trás ou para a frente
• window.history.pushState(data, title [, url ] ) -> guarda dados no history
• window.history.replaceState(data, title [, url ] ) -> substitui os dados do history
• window.onpopstate -> evento que ocorre quando se obtem os dados do history
6 – Troca de Mensagens entre Janelas
O HTML5 permite enviar mensagens
em cross-window ou cross-domain.

Por exemplo, na página A, a página B
aparece num <iframe>. Podemos enviar
mensagens de A para B. Isto é cross-
window.
Se a página B estiver hospedada num
outro servidor, isto é cross-domain, que
era proibido anteriormente.




http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html
7 – Uso de Vídeo e Áudio
HTML5 reproduz vídeos através do elemento <video>.

O formato de vídeo adoptado pelo w3c é o “Theora” (.ogg), pois é open-
source, e sem direitos de copyright. (condição para ser adoptado pelo w3c).

http://www.w3.org/TR/html5/the-iframe-
element.html#the-video-element
Exemplohttp://www.w3.org/2010/05/video/mediaevents.html
Para converter um outro formato para o formato .ogg, existem várias
aplicações, entre elas algumas gratuitas.
Exemplo: Miro Video Converter
Video API



Tem os seguintes atributos:
• autoplay – true ou false – toca automaticamente
• controls – coloca os botões de controlo do vídeo
• height – largura do vídeo
• loop – quando chega ao fim recomeça
• poster – o url de uma imagem, caso o vídeo não esteja disponível
• preload – none – não faz o preload do vídeo
           - metadata – carrega a informação do vídeo(dimensões, 1º frame, etc.)
           - auto – o browser decido o que fazer
• src – o url do vídeo
• width – a altura do vídeo
• onerror – o evento que dispara caso haja um erro no vídeo

 www.w3.org/TR/html5/video.html
<!DOCTYPE html>
 <html>
      <head>
        <title> HTML 5 Video
         </title>
      </head>
      <body>
      <h1>
           HTML 5 Video
      </h1>

  <video width="360" height="240" autoplay="false" controls="true” loop>
         <source src="video.mp4" type="video/mp4"/>
         <source src="video.ogg" type="video/ogg"/>
         <source src="video.webm" type="video/webm"/>
         <p> Video cannot be displayed </p>
 </video>

         <audio src="L.A. Woman.theora.ogv" autoplay=true controls>
        </body>
    </html>
8 – Armazenamento de dados
O html, não tem como guardar os dados entre vários acessos às página. Quando se
faz uma atualização à página, os dados de um formulário são apagados. Para dar a
volta a isso usa-se código de servidor.

Com a introduçaõ do HTML5, isso deixou de ser necessário.
Pode-se guardar os dados ou no servidor, na sessão iniciada pelo browser; ou no
próprio browser.
Trabalho Módulo 2

 Elaborar um documento que explique como funcionam as seguintes
 capacidades do HTML5:

 -Trabalhar com o Histórico do Browser
 -Troca de Mensagens entre Janelas
 -Armazenamento de dados
 Para cada uma delas, criar páginas de exemplos, que demonstrem
    essas capacidades

Mais conteúdo relacionado

Destaque

004 11 jan. 2015 pm داود (4) رجل حسب قلبه 1 صم15.23 18 (1)
004 11 jan. 2015 pm  داود (4) رجل حسب قلبه 1 صم15.23 18 (1)004 11 jan. 2015 pm  داود (4) رجل حسب قلبه 1 صم15.23 18 (1)
004 11 jan. 2015 pm داود (4) رجل حسب قلبه 1 صم15.23 18 (1)Ibrahimia Church Ftriends
 
Fb content images week 2 nov
Fb content images   week 2 novFb content images   week 2 nov
Fb content images week 2 novNethravathi Reddy
 
M.Phil Computer Science Parallel and Distributed System Projects
M.Phil Computer Science Parallel and Distributed System ProjectsM.Phil Computer Science Parallel and Distributed System Projects
M.Phil Computer Science Parallel and Distributed System ProjectsVijay Karan
 
IEEE 2014 C# Projects
IEEE 2014 C# ProjectsIEEE 2014 C# Projects
IEEE 2014 C# ProjectsVijay Karan
 
Branding workshop Upplevelseproduktion Piteå
Branding workshop Upplevelseproduktion PiteåBranding workshop Upplevelseproduktion Piteå
Branding workshop Upplevelseproduktion PiteåLOVEATWORK
 
Journal of the Taiwan Institute of Chemical Engineers 0 0 0 (2016) 1–20
Journal of the Taiwan Institute of Chemical Engineers 0 0 0 (2016) 1–20Journal of the Taiwan Institute of Chemical Engineers 0 0 0 (2016) 1–20
Journal of the Taiwan Institute of Chemical Engineers 0 0 0 (2016) 1–20Al Baha University
 
Het Nieuwe Werken En Tijdregistratie
Het Nieuwe Werken En TijdregistratieHet Nieuwe Werken En Tijdregistratie
Het Nieuwe Werken En TijdregistratieBieke Van Baelen
 
العبادة و التسبيح كوركيوس متى
العبادة و التسبيح   كوركيوس متىالعبادة و التسبيح   كوركيوس متى
العبادة و التسبيح كوركيوس متىIbrahimia Church Ftriends
 
الوصايا العشر ـ الوصية الثانية القس كرم لمعى صباح الأحد 27 مارس 2011
الوصايا العشر ـ الوصية الثانية    القس كرم لمعى   صباح الأحد 27 مارس 2011الوصايا العشر ـ الوصية الثانية    القس كرم لمعى   صباح الأحد 27 مارس 2011
الوصايا العشر ـ الوصية الثانية القس كرم لمعى صباح الأحد 27 مارس 2011Ibrahimia Church Ftriends
 
السعوديه و الاخوان المسلمون محمد ابو الاسعاد
السعوديه و الاخوان المسلمون   محمد ابو الاسعادالسعوديه و الاخوان المسلمون   محمد ابو الاسعاد
السعوديه و الاخوان المسلمون محمد ابو الاسعادIbrahimia Church Ftriends
 
4.1 PABLO DIEGO AND GALVAN
4.1 PABLO DIEGO AND GALVAN4.1 PABLO DIEGO AND GALVAN
4.1 PABLO DIEGO AND GALVANMarce Bravo
 
IEEE 2014 Matlab Projects
IEEE 2014 Matlab ProjectsIEEE 2014 Matlab Projects
IEEE 2014 Matlab ProjectsVijay Karan
 
79 الوصية الثامنة . لا تسرق القس كرم لمعى صباح الأحد 3 يوليو 2011
79 الوصية الثامنة . لا تسرق  القس كرم لمعى  صباح الأحد 3 يوليو 201179 الوصية الثامنة . لا تسرق  القس كرم لمعى  صباح الأحد 3 يوليو 2011
79 الوصية الثامنة . لا تسرق القس كرم لمعى صباح الأحد 3 يوليو 2011Ibrahimia Church Ftriends
 

Destaque (20)

004 11 jan. 2015 pm داود (4) رجل حسب قلبه 1 صم15.23 18 (1)
004 11 jan. 2015 pm  داود (4) رجل حسب قلبه 1 صم15.23 18 (1)004 11 jan. 2015 pm  داود (4) رجل حسب قلبه 1 صم15.23 18 (1)
004 11 jan. 2015 pm داود (4) رجل حسب قلبه 1 صم15.23 18 (1)
 
Cap.5
Cap.5Cap.5
Cap.5
 
Fb content images week 2 nov
Fb content images   week 2 novFb content images   week 2 nov
Fb content images week 2 nov
 
M.Phil Computer Science Parallel and Distributed System Projects
M.Phil Computer Science Parallel and Distributed System ProjectsM.Phil Computer Science Parallel and Distributed System Projects
M.Phil Computer Science Parallel and Distributed System Projects
 
IEEE 2014 C# Projects
IEEE 2014 C# ProjectsIEEE 2014 C# Projects
IEEE 2014 C# Projects
 
Branding workshop Upplevelseproduktion Piteå
Branding workshop Upplevelseproduktion PiteåBranding workshop Upplevelseproduktion Piteå
Branding workshop Upplevelseproduktion Piteå
 
Presentació
PresentacióPresentació
Presentació
 
Journal of the Taiwan Institute of Chemical Engineers 0 0 0 (2016) 1–20
Journal of the Taiwan Institute of Chemical Engineers 0 0 0 (2016) 1–20Journal of the Taiwan Institute of Chemical Engineers 0 0 0 (2016) 1–20
Journal of the Taiwan Institute of Chemical Engineers 0 0 0 (2016) 1–20
 
Paul Sansone JR
Paul Sansone  JR Paul Sansone  JR
Paul Sansone JR
 
Het Nieuwe Werken En Tijdregistratie
Het Nieuwe Werken En TijdregistratieHet Nieuwe Werken En Tijdregistratie
Het Nieuwe Werken En Tijdregistratie
 
оптические явления в атмосфере
оптические явления в атмосфереоптические явления в атмосфере
оптические явления в атмосфере
 
Hebrews
HebrewsHebrews
Hebrews
 
العبادة و التسبيح كوركيوس متى
العبادة و التسبيح   كوركيوس متىالعبادة و التسبيح   كوركيوس متى
العبادة و التسبيح كوركيوس متى
 
الوصايا العشر ـ الوصية الثانية القس كرم لمعى صباح الأحد 27 مارس 2011
الوصايا العشر ـ الوصية الثانية    القس كرم لمعى   صباح الأحد 27 مارس 2011الوصايا العشر ـ الوصية الثانية    القس كرم لمعى   صباح الأحد 27 مارس 2011
الوصايا العشر ـ الوصية الثانية القس كرم لمعى صباح الأحد 27 مارس 2011
 
السعوديه و الاخوان المسلمون محمد ابو الاسعاد
السعوديه و الاخوان المسلمون   محمد ابو الاسعادالسعوديه و الاخوان المسلمون   محمد ابو الاسعاد
السعوديه و الاخوان المسلمون محمد ابو الاسعاد
 
4.1 PABLO DIEGO AND GALVAN
4.1 PABLO DIEGO AND GALVAN4.1 PABLO DIEGO AND GALVAN
4.1 PABLO DIEGO AND GALVAN
 
IEEE 2014 Matlab Projects
IEEE 2014 Matlab ProjectsIEEE 2014 Matlab Projects
IEEE 2014 Matlab Projects
 
02 viga parede
02 viga parede02 viga parede
02 viga parede
 
Markdayturismo
MarkdayturismoMarkdayturismo
Markdayturismo
 
79 الوصية الثامنة . لا تسرق القس كرم لمعى صباح الأحد 3 يوليو 2011
79 الوصية الثامنة . لا تسرق  القس كرم لمعى  صباح الأحد 3 يوليو 201179 الوصية الثامنة . لا تسرق  القس كرم لمعى  صباح الأحد 3 يوليو 2011
79 الوصية الثامنة . لا تسرق القس كرم لمعى صباح الأحد 3 يوليو 2011
 

Semelhante a HTML 5 Canvas e Drag and Drop

Semelhante a HTML 5 Canvas e Drag and Drop (20)

Canvas element
Canvas elementCanvas element
Canvas element
 
HTML5 & CSS3
HTML5 & CSS3HTML5 & CSS3
HTML5 & CSS3
 
CSS & JQquery
CSS & JQqueryCSS & JQquery
CSS & JQquery
 
Cobol Web com Net Express 5.1 - Parte 3
Cobol Web com Net Express 5.1 - Parte 3Cobol Web com Net Express 5.1 - Parte 3
Cobol Web com Net Express 5.1 - Parte 3
 
Laboratório Web 2013-2014 - CSS3
Laboratório Web 2013-2014 - CSS3Laboratório Web 2013-2014 - CSS3
Laboratório Web 2013-2014 - CSS3
 
Design Responsivo com Sass
Design Responsivo com SassDesign Responsivo com Sass
Design Responsivo com Sass
 
Desafios no desenvolvimento de uma aplicação real com Flex @ FUGSC
Desafios no desenvolvimento de uma aplicação real com Flex @ FUGSCDesafios no desenvolvimento de uma aplicação real com Flex @ FUGSC
Desafios no desenvolvimento de uma aplicação real com Flex @ FUGSC
 
Javascript + jQuery
Javascript + jQueryJavascript + jQuery
Javascript + jQuery
 
Web 3.0
Web 3.0Web 3.0
Web 3.0
 
Edição de conteúdo web usando Javascript de ponta a ponta
Edição de conteúdo web usando Javascript de ponta a pontaEdição de conteúdo web usando Javascript de ponta a ponta
Edição de conteúdo web usando Javascript de ponta a ponta
 
Criando sites com estilos
Criando sites com estilosCriando sites com estilos
Criando sites com estilos
 
TDC2016SP - Trilha BigData
TDC2016SP - Trilha BigDataTDC2016SP - Trilha BigData
TDC2016SP - Trilha BigData
 
XHTML Básico
XHTML BásicoXHTML Básico
XHTML Básico
 
Introdução a HTML5
Introdução a HTML5Introdução a HTML5
Introdução a HTML5
 
Responsive web design
Responsive web designResponsive web design
Responsive web design
 
HTML + CSS
HTML + CSSHTML + CSS
HTML + CSS
 
Mini Curso - jQuery - FMU
Mini Curso - jQuery - FMUMini Curso - jQuery - FMU
Mini Curso - jQuery - FMU
 
Web em grande estilo com CSS 3
Web em grande estilo com CSS 3Web em grande estilo com CSS 3
Web em grande estilo com CSS 3
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Web 2.0 com Ajax: JQuery/PHP (Aula 02)
Web 2.0 com Ajax: JQuery/PHP (Aula 02)Web 2.0 com Ajax: JQuery/PHP (Aula 02)
Web 2.0 com Ajax: JQuery/PHP (Aula 02)
 

HTML 5 Canvas e Drag and Drop

  • 1. Paradigmas Emergentes para a WEB HTML 5 ANTÓNIO MARQUES, 2012 amarques@utad.pt Gabinete F1.21 Eng1
  • 2. Índice resumido 1. Desenhar com o elemento CANVAS 2. Drag and Drop 3. Controlos de Formulários 4. Edição Inline 5. Trabalhar com o Histórico do Browser 6. Troca de Mensagens entre Janelas 7. Uso de Vídeo e Áudio 8. Armazenamento de dados
  • 3. 1 - O elemento CANVAS O elemento CANVAS é usado para desenhar gráficos. É criado com a seguinte instrução: <canvas height=“xxx” width =“yyy”> </canvas> Para desenhar no canvas usa-se JavaScript. Pode-se desenhar linhas, arcos, formas complexas, texto, imagens, etc. O W3C definiu uma API (Application Programming Interface), onde definiu o nome das funções e como devem ser usadas. http://www.w3.org/TR/2dcontext/
  • 4. CANVAS API A API define atributos dos elementos e as funções em JavaScript. É necessário atribuir alguns atributos antes de usar as funções de desenho. Exemplo: Canvas1.fillStyle = xxx; Canvas1.fillRectangle(x,y,dx,dy); Lista de atributos e funções: Styling • attribute any strokeStyle; // (default black) • attribute any fillStyle; // (default black) Line Styles • attribute DOMString lineCap; // “butt”, “round”, “square” (default “butt”) • attribute DOMString lineJoin; // “miter”, “round”, “bevel” ) (default “miter”) • attribute float lineWidth; // (default 1) • attribute float miterLimit; // (default 10)
  • 5. Shadows • attribute float shadowBlur; // (default 0) • attribute DOMString shadowColor; // (default transparent black) • attribute float shadowOffsetX; // (default 0) • attribute float shadowOffsetY; // (default 0) Rectangles • clearRect(float x, float y, float w, float h); • fillRect(float x, float y, float w, float h); • strokeRect(float x, float y, float w, float h); Complex Shapes • arc(float x, float y, float radius, float startAngle, float endAngle, boolean anticlockwise); • arcTo(float x1, float y1, float x2, float y2, float radius); • beginPath(); • bezierCurveTo(float cp1x, float cp1y, float cp2x, float cp2y, float x, float y); • clip(); • closePath(); • fill(); • lineTo(float x, float y); • moveTo(float x, float y); • quadraticCurveTo(float cpx, float cpy, float x, float y); • rect(float x, float y, float w, float h); • stroke(); • boolean isPointInPath(float x, float y);
  • 6. Text • attribute DOMString font; // (default 10px sans-serif) • attribute DOMString textAlign; // “start”, “end”, “left”, “right”, “center” (default: “start”) • attribute DOMString textBaseline; // “top”, “hanging”, “middle”, “alphabetic”, “ideographic”, “bottom” (default: “alphabetic”) • fillText(DOMString text, float x, float y, optional float maxWidth); • TextMetrics measureText(DOMString text); • strokeText(DOMString text, float x, float y, optional float maxWidth); Images • drawImage(HTMLImageElement image, float dx, float dy, optional float dw, float dh); • drawImage(HTMLImageElement image, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh); • drawImage(HTMLCanvasElement image, float dx, float dy, optional float dw, float dh); • drawImage(HTMLCanvasElement image, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh); • drawImage(HTMLVideoElement image, float dx, float dy, optional float dw, float dh); • drawImage(HTMLVideoElement image, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh); Transformations • rotate(float angle); • scale(float x, float y); • translate(float x, float y);
  • 7. Exemplo de uso de CANVAS 1. Criar um ficheiro canvas.html com um editor de texto. * 2. Escrever o seguinte código, para criar o Canvas e fazer o setup do JavaScript: <!DOCTYPE html> <html> <head> <title> Exemplo de Canvas </title> http://www.activestate.com/komodo- <script type="text/javascript"> functionedit/downloads loader() { } </script> </head> <body onload="loader()"> <h1>Exemplo de Canvas</h1> <canvas id="canvas" height="500" width="600"> </canvas> </body> </html> •http://www.activestate.com/komodo-edit/downloads Editor gratuito, com versões para Mac, Linux e Windows. Com Intellisense para HTML 5
  • 8. 3. Adicionar o código JavaScript para criar um objecto do elemento Canvas <script type="text/javascript"> function loader() { var canvas = document.getElementById('canvas'); var canvas1= canvas.getContext('2d'); } </script> 4. Gravar o ficheiro no formato de texto. 5. Experimentar em vários Browsers.
  • 9. Desenhar Rectângulos 6. Escrever o seguinte código para criar 3 rectângulos de diferentes cores function loader() { var canvas = document.getElementById('canvas'); var canvas1= canvas.getContext('2d'); //Rectângulos canvas1.fillStyle="rgba(0,0,200,1)"; //Côr Azul canvas1.fillRect(30,30,75,70); canvas1.fillStyle="rgb(200,200,0)"; canvas1.fillRect(70,50,55,70); canvas1.fillStyle = "rgba(200, 0, 0, 1)"; canvas1.fillRect(90, 50, 75, 50); } 7. Gravar e experimentar
  • 10. Desenhar Linhas 1. Abrir o ficheiro e acrescentar o seguinte código: function loader() { //Desenhar Triângulos canvas1.beginPath(); canvas1.strokeStyle = "rgba(200, 0, 0, 0.5)"; canvas1.moveTo(110, 205); canvas1.lineTo(110, 125); canvas1.lineTo(30, 205); canvas1.closePath(); canvas1.stroke(); canvas1.beginPath(); canvas1.moveTo(100, 205); canvas1.lineTo(100, 125); canvas1.lineTo(20, 205); canvas1.closePath(); canvas1.stroke(); canvas1.beginPath(); canvas1.moveTo(90, 205); canvas1.lineTo(90, 125); canvas1.lineTo(10, 205); canvas1.closePath(); canvas1.stroke(); }
  • 11. Desenhar Linhas Preenchidas 1. Acrescentar o seguinte código: function loader() { //Filled triangle canvas1.fillStyle = "rgba(0, 200, 0, 0.5)"; canvas1.beginPath(); canvas1.moveTo(225, 25); canvas1.lineTo(305, 25); canvas1.lineTo(225, 105); canvas1.closePath(); canvas1.fill(); }
  • 12. Desenhar Curvas de Bezier function loader() { // Heart canvas1.fillStyle = "rgba(200, 0, 0, 0.5)"; canvas1.beginPath(); canvas1.moveTo(75, 250); canvas1.bezierCurveTo(75, 247, 70, 235, 50, 235); canvas1.bezierCurveTo(20, 235, 20, 272.5, 20, 272); canvas1.bezierCurveTo(20, 290, 40, 312, 75, 330); canvas1.bezierCurveTo(110, 312, 130, 290, 130, 272); canvas1.bezierCurveTo(130,272.5, 130, 235, 100, 235); canvas1.bezierCurveTo(85, 235, 75, 247, 75, 250); canvas1.closePath(); canvas1.fill(); }
  • 13. Desenhar Curvas Quadráticas function loader() { //Quadratic curves canvas1.strokeStyle = "rgba(0, 0, 0, 1)"; canvas1.beginPath(); canvas1.moveTo(275, 125); canvas1.quadraticCurveTo(225, 125, 225, 162); canvas1.quadraticCurveTo(260, 200, 265, 200); canvas1.quadraticCurveTo(325, 200, 325, 162); canvas1.quadraticCurveTo(325, 125, 275, 125); canvas1.closePath(); canvas1.stroke(); }
  • 14. Desenhar Arcos function loader() { // Arcs canvas1.beginPath(); canvas1.arc(275,275, 50, 0, Math.PI * 2, true); canvas1.moveTo(310, 275); canvas1.arc(275, 275, 35, 0, 0.75 * Math.PI, false); canvas1.moveTo(300, 255); canvas1.arc(265, 255, 35, 0, 0.5 * Math.PI, false); canvas1.moveTo(280, 255); canvas1.arc(245, 255, 35, 0, 0.2 * Math.PI, false); canvas1.closePath(); canvas1.stroke(); }
  • 15. Desenhar Texto function loader() { //Texto canvas1.font = 'italic 40px sans-serif'; canvas1.strokeText("Olá!", 50, 400); }
  • 16. 2 - Drag and Drop Com o suporte de Drag and Drop, podemos deslocar elementos e texto pelo browser, com o uso do rato ou outro dispositivo apontador. Como exemplo, podemos deslocar itens para um cesto de compras; configurar a nossa homepage; etc. O Drag and Drop é suportado com a criação de novos atributos dos elementos, como o atributo draggable que colocado a true permite a esse elemento ser deslocado. No entanto todo o processamento é feito em JavaScript. A API para trabalhar com o Drag and Drop está definida em: http://dev.w3.org/html5/spec/dnd.html
  • 17. Drag and Drop negado Drag and Drop permitido
  • 18. Criar um ficheiro, dragandrop.html, e escrever este código <!DOCTYPE HTML> </head> <html> <body> <head> <h1>Drag and Drop Example</h1> <title> <div id="target1"> Drag and Drop Example <div id="draggable1">1 </title> </div> <div id="draggable2">2 <style type="text/css"> </div> #target1, #target2, #target3 <div id="draggable3">3 { </div> float:left; width:250px; height:250px; </div> padding:10px; margin:10px; <div id="target2"> } </div> #draggable1, #draggable2, #draggable3 <div id="target3"> { </div> width:75px; height:70px; padding:5px; </body> margin:5px; </html> } #target1 {background-color:cyan;} #target2 {background-color:blue;} #target3 {background-color:cyan;} #draggable1 {background-color: orange;} #draggable2 {background-color: orange;} #draggable3 {background-color: orange;} </style>
  • 19. Colocar o atributo draggable nos elementos que se querem mover: </head> <body> <h1>Drag and Drop Example</h1> <div id="target1"> <div id="draggable1” draggable="true" >1 </div> <div id="draggable2” draggable="true" >2 </div> <div id="draggable3” draggable="true" >3 </div> </div> <div id="target2"> </div> <div id="target3"> </div> </body> </html> Experimentar em vários browsers
  • 20. Colocar os atributos nos elementos de destino: </head> ondragenter – evento que ocorre <body> <h1>Drag and Drop Example</h1> quando um elemento que está a ser <div id="target1“ arrastado entra na área do elemento ondragenter="return enter(event)" ondragover="return over(event, this)" ondrop="return drop(event)" > ondragover - evento que ocorre quando </div> o elemento que está a ser arrastado está <div id="target2“ ondragenter="return enter(event)" sobre o elemento ondragover="return over(event,this)" ondrop="return drop(event)" > ondrop - evento que ocorre quando o </div> <div id="target3“ elemento é largado em cima do ondragenter="return enter(event)" elemento ondragover="return over(event,this)" ondrop="return drop(event)" > </div> </body> </html>
  • 21. Colocar os atributos nos elementos a arrastar: . . <div id="draggable1" draggable="true" ondragstart – evento que ocorre ondragstart="return start(event)" quando o elemento draggable, ondragend="return end(event)">1 </div> começa a ser movimentado <div id="draggable2" draggable="true“ ondragstart="return start(event)“ ondragend – evento que ocorre ondragend="return end(event)">2 quando se larga o elemento </div> <div id="draggable3" draggable="true“ ondragstart="return start(event)“ ondragend="return end(event)">3 </div> . .
  • 22. Implementar a função start() . . <script type="text/javascript"> function start(e) { e.dataTransfer.effectedAllowed=“move”; e.dataTransfer.setData("Data",e.target.getAttribute('id')); e.dataTransfer.setDragImage(e.target, 0, 0); return true; } </script> </head> . . No parâmetro e define-se os dados que vão ser transmitidos, e o modo. Neste caso vai executar um move, coloca, com setData, o id do elemento que está a ser arrastado. A função setDragImage, define a imagem a ser transferida, neste caso o elemento a ser arrastado, e um offset, neste caso 0,0
  • 23. Implementar a função enter() . . <script type="text/javascript"> function enter(e) { return true; } </script> </head> . .
  • 24. Implementar a função over() . . <script type="text/javascript"> function over(e, element) { var iddraggable = e.dataTransfer.getData("Data"); var id = element.getAttribute('id'); if(id==‘target1’) return false; if((id=='target2') && iddraggable == 'draggable3') return false; else if(id=='target3' && (iddraggable == 'draggable1' || iddraggable == 'draggable2')) return false; else return true; } </script> </head> . .
  • 25. Implementar a função drop() <script type="text/javascript"> function drop(e) { var iddraggable=e.dataTransfer.getData("Data"); e.target.appendChild(document.getElementById(iddraggable)); e.stopPropagation(); return false; } </script> </head> Implementar a função end() <script type="text/javascript"> function end(e) { e.dataTransfer.clearData("Data"); return true; } </script> </head>
  • 26. 3 - Controlos de Formulários O HTML 5 introduziu novos tipos de controlos para a introdução de dados num formulário. Estes controlos estendem o controlo <input>, acrescentando outro tipos aos já existentes (text, radio,etc.). http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html
  • 27. Os controlos de formulário são criados com o elemento <input>, definindo no atributo type, qual o tipo de controlo:
  • 28. Criar um ficheiro webform.html, e escrever este código <!DOCTYPE html> <html> <head> <title> Web Form Example </title> </head> <body> <h1>Web Form Example</h1> <form method=“post” action=“webforms.php”> <table border=“1” cellpadding=“5”> . . . </table> <input type=“submit” value=“Submit”> </form> </body> </html>
  • 29. Introduzir o controlo default <table border=“1” cellpadding=“5”> <tr> <td>Deafult</td> <td><input name=“name” placeholder=“Introduza o login” required=true autofocus> </td> </tr> . </table> <input type=“submit” value=“Submit”> </form> </body> </html> Introduzir o controlo Url <table border=“1” cellpadding=“5”> . </tr> <tr> <td>URL</td><td><input name=“url” type=“url”></td> </tr> </table> <input type=“submit” value=“Submit”> </form> </body> </html>
  • 30. Introduzir o controlo email <table border=“1” cellpadding=“5”> . <tr> <td>Email</td> <td><input name=“email” type=“email”></td> </tr> . </table> <input type=“submit” value=“Submit”> </form> </body> </html> Introduzir os controlos Range e number <table border=“1” cellpadding=“5”> . <tr> <td>Range</td><td><input name=“range” type=“range” min=“0” max=“100” step=“5” value=“40”></td> </tr> <tr> <td>Number</td><td><input name=“number” type=“number” min=“0” max=“100” step=“5” value=“40”></td> </tr> </table>
  • 31. Introduzir os controlos de Data e Hora <table border=“1” cellpadding=“5”> <tr> <td>Date</td><td><input name=“date” type=“date”></td> </tr> <tr> <td>Week</td><td><input name=“week” type=“week”></td> </tr> <tr> <td>Month</td><td><input name=“month” type=“month”></td> </tr> <tr> <td>Time</td><td><input name=“time” type=“time”></td> </tr> <tr> <td>Datetime</td><td><input name=“datetime” type=“datetime”></td> </tr> <tr> <td>Local Datetime</td><td><input name=“datetimelocal” type=“datetime-local”></td> </tr> </table>
  • 32. Introduzir o controlo Color <table border=“1” cellpadding=“5”> . <tr> <td>Color</td><td><input name=“color” type=“color”></td> </tr> </table> Introduzir o controlo Search <table border=“1” cellpadding=“5”> . <tr> <td>Search Query</td><td><input name=“query” type=“query”></td> </tr> </table>
  • 33. Criar o ficheiro webforms.php, que vai atender à submissão do formulário <html> <head> <title> Reading data from datetime controls </title> </head> <body> <h1> Lêr os dados do contolo Datetime </h1> Introduziu: <?php echo $_REQUEST['datetime']; ?> </body> </html>
  • 34. 4 – Edição Inline HTML5 especifica que se pode fazer elementos editáveis, ou seja, permitir que o utilizador edite o seu conteúdo. Isso não quer dizer que estamos a falar de campos de texto, mas sim qualquer tipo de elementos, tais como o elemento <div>. Além disso, podemos fazer um documento inteiro editável, incluindo elemento <iframe>. Também se pode fazer a verificação ortográfica do texto introduzido.
  • 35. Para usar a edição usa-se três atributos: • contenteditable – torna um elemento HTML editável • designmode – torna todo o documento editável • spellcheck – activa o corrector ortográfico Exemplo do uso do atribbuto contenteditable Criar o ficheiro editdiv.html <!DOCTYPE html> <html> <head> <title> Editable &lt;div&gt; Element </title> </head> <body> <h1>Editable &lt;div&gt; Element</h1> . . </body> </html>
  • 36. Introduzir o seguinte div com o atributo contenteditable a true <body> <h1>Editable &lt;div&gt; Element</h1> <br> . <div id="div" style='border:solid black; height: 300px; width: 400px' contenteditable="true“> </div> </body> </html> Introduzir o código para criar o botão Negrito e executar o comando ‘bold’ <body> <h1>Editable &lt;div&gt; Element</h1> <div> <input type="button" value=“Negrito" onclick="document.execCommand('bold', false, null);"> </div> . <br> <div id="div" style='border:solid black; height: 300px; width: 400px' contenteditable="true"> </div> </body>
  • 37. Introduzir os restantes botões: <body> <h1>Editable &lt;div&gt; Element</h1> <div> <input type="button" value=“Negrito" onclick="document.execCommand('bold', false, null);"> <input type="button" value="Itálico" onclick="document.execCommand('italic', false, null);"> <input type="button" value="Sublinhado" onclick="document.execCommand('underline', false, null);"> <input type="button" value="Criar Link" onclick="createLink();"> <input type="button" value="Mostar Source" onclick="showSource();"> </div> <br> <div id="div" style='border:solid black; height: 300px; width: 400px' contenteditable="true"> </div> </body>
  • 38. Introduzir as funções de JavaScript para os botões “Criar Link” e “Mostrar Source” </title> <script type="text/javascript"> function showSource() { var content = document.getElementById("div").innerHTML; content.replace(/</g, '&lt;'); content.replace(/>/g, '&gt;'); alert(content); } function createLink() { var url = prompt("Enter URL:", "http://"); if (url) document.execCommand("createlink", false, url); } </script>
  • 39. 5 – Trabalhar com o Histórico do Browser O HTML5 permite o controle sobre o histórico do navegador. O objeto History, permite avançar e retroceder, de página para página no navegador, o que significa que se pode usá-lo por exemplo, para voltar três páginas atrás. Também se pode armazenar dados num objeto de estado no history. Ou seja, pode-se adicionar dados no objeto de estado e, em seguida, para armazená-lo com a página atual. Os dados guardados n o objeto de estado, pode ser recuperado, o que permite passar dados de uma página para outra.
  • 40. O object history faz parte do objecto window, assim é referido window.history. Atributos e funções definidas na API: • window.history.length -> número de páginas no history • window.history.back() -> vai para a página anterior • window.history.forward() -> vai para a página seguinte • window.history.go([delta]) -> vai para delta páginas para trás ou para a frente • window.history.pushState(data, title [, url ] ) -> guarda dados no history • window.history.replaceState(data, title [, url ] ) -> substitui os dados do history • window.onpopstate -> evento que ocorre quando se obtem os dados do history
  • 41. 6 – Troca de Mensagens entre Janelas O HTML5 permite enviar mensagens em cross-window ou cross-domain. Por exemplo, na página A, a página B aparece num <iframe>. Podemos enviar mensagens de A para B. Isto é cross- window. Se a página B estiver hospedada num outro servidor, isto é cross-domain, que era proibido anteriormente. http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html
  • 42. 7 – Uso de Vídeo e Áudio HTML5 reproduz vídeos através do elemento <video>. O formato de vídeo adoptado pelo w3c é o “Theora” (.ogg), pois é open- source, e sem direitos de copyright. (condição para ser adoptado pelo w3c). http://www.w3.org/TR/html5/the-iframe- element.html#the-video-element Exemplohttp://www.w3.org/2010/05/video/mediaevents.html Para converter um outro formato para o formato .ogg, existem várias aplicações, entre elas algumas gratuitas. Exemplo: Miro Video Converter
  • 43. Video API Tem os seguintes atributos: • autoplay – true ou false – toca automaticamente • controls – coloca os botões de controlo do vídeo • height – largura do vídeo • loop – quando chega ao fim recomeça • poster – o url de uma imagem, caso o vídeo não esteja disponível • preload – none – não faz o preload do vídeo - metadata – carrega a informação do vídeo(dimensões, 1º frame, etc.) - auto – o browser decido o que fazer • src – o url do vídeo • width – a altura do vídeo • onerror – o evento que dispara caso haja um erro no vídeo www.w3.org/TR/html5/video.html
  • 44. <!DOCTYPE html> <html> <head> <title> HTML 5 Video </title> </head> <body> <h1> HTML 5 Video </h1> <video width="360" height="240" autoplay="false" controls="true” loop> <source src="video.mp4" type="video/mp4"/> <source src="video.ogg" type="video/ogg"/> <source src="video.webm" type="video/webm"/> <p> Video cannot be displayed </p> </video> <audio src="L.A. Woman.theora.ogv" autoplay=true controls> </body> </html>
  • 45. 8 – Armazenamento de dados O html, não tem como guardar os dados entre vários acessos às página. Quando se faz uma atualização à página, os dados de um formulário são apagados. Para dar a volta a isso usa-se código de servidor. Com a introduçaõ do HTML5, isso deixou de ser necessário. Pode-se guardar os dados ou no servidor, na sessão iniciada pelo browser; ou no próprio browser.
  • 46. Trabalho Módulo 2 Elaborar um documento que explique como funcionam as seguintes capacidades do HTML5: -Trabalhar com o Histórico do Browser -Troca de Mensagens entre Janelas -Armazenamento de dados Para cada uma delas, criar páginas de exemplos, que demonstrem essas capacidades