HTML5 자바스크립트 API

“Open platform for rich Web applications,”

별도의 브라우저 플러그인을 설치하지 않고
네이티브 애플리케이션 수준의
리치한 웹 애플리케이션을 개발한다.

Javascript API

  • New Media Elements
  • Desktop Experiences
  • Support Offlines
  • Realtime Comunications

New Media Elements

  • Audio & Video Elements
  • Canvas Element
  • SVG Element

Audio and Video

<audio src="sound.mp3" controls></audio>
document.getElementById("audio").muted=false;

<video src='movie.mp4' autoplay controls ></video>
document.getElementById("video").play();

Canvas

<canvas id="canvas" width="838" height="220"></canvas>

<script>
var canvasContext = document.getElementById("canvas").getContext("2d");
canvasContext.fillRect(250, 25, 150, 100);

canvasContext.beginPath();
canvasContext.arc(450, 110, 100, Math.PI * 1/2, Math.PI * 3/2);
canvasContext.lineWidth = 15;
canvasContext.lineCap = 'round';
canvasContext.strokeStyle = 'rgba(255, 127, 0, 0.5)';
canvasContext.stroke();
</script>
          

Canvas example

SVG Element

<html>
  <svg>
    <circle id="myCircle" class="important" cx="50%" cy="50%" r="100"
        fill="url(#myGradient)"
        onmousedown="alert('hello');"/>
  </svg>
</html>

SVG example

Desktop Experiences

  • Notifications
  • Drag and Drop
  • File API
  • Web Workers
  • WebGL 3D Graphics

New Selectors

Finding elements by class (DOM API)

var el = document.getElementById('section1');
el.focus();

var els = document.getElementsByTagName('div');
els[0].focus();

var els = document.getElementsByClassName('section');
els[0].focus();

Finding elements by CSS syntax (Selectors API)

var els = document.querySelectorAll("ul li:nth-child(odd)");
var els = document.querySelectorAll("table.test > tr > td");

Notifications

if (window.webkitNotifications.checkPermission() == 0) {
  // you can pass any url as a parameter
  window.webkitNotifications.createNotification(tweet.picture, tweet.title,
    tweet.text).show();
} else {
  window.webkitNotifications.requestPermission();
}

Note: Use this button if you also want to reset the permissions


Enter your twitter user name to show your last tweet as a notification

Web Workers

main.js:
  var worker = new Worker(‘extra_work.js');
  worker.onmessage = function (event) { alert(event.data); };

extra_work.js:
  // do some work; when done post message.
  postMessage(some_data);

Try to drag the map while calculating the complex route (you will only be allowed to do that if you use workers)

Drag and Drop

document.addEventListener('dragstart', function(event) {
  event.dataTransfer.setData('text', 'Customized text');
  event.dataTransfer.effectAllowed = 'copy';
}, false);
  1. Select text and drag (original text will be dropped)
  2. Select text and drag (dragged text data will be altered from original)
Source Data
Drop Area

File API

document.getElementById("files-upload").onchange = function () {
  var li,
      file,
      fileInfo,
      fileList = document.getElementById("file-list");
  fileList.innerHTML = "";
  for (var i=0, il=files.length; i<il; i++) {
    li = document.createElement("li");
    file = this.files[i];
    fileInfo = "<p><strong>Name:</strong> " + file.name + "</p>";
    fileInfo += "<p><strong>Size:</strong> " + file.size + " bytes</p>";
    fileInfo += "<p><strong>Type:</strong> " + file.type + "</p>";
    li.innerHTML = fileInfo;
    fileList.appendChild(li);
  };
};

Choose file(s)

Uploaded files

  • (no files uploaded yet)

WebGL 3D Graphics

<canvas id="canvas" width="838" height="220"></canvas>

<script>
  var gl = document.getElementById("canvas").getContext("experimental-webgl");
  gl.viewport(0, 0, canvas.width, canvas.height);
  ...
</script>

Support Offlines

  • Web Storage
  • Web SQL Database
  • IndexedDB
  • Application Cache API

Web Storage

// use localStorage for persistent storage
// use sessionStorage for per tab storage
textarea.addEventListener('keyup', function () {
  window.localStorage['value'] = area.value;
  window.localStorage['timestamp'] = (new Date()).getTime();
}, false);
textarea.value = window.localStorage['value'];

Save text value on the client side (crash-safe)

Web SQL Database

var db = window.openDatabase("Database Name", "Database Version");
db.transaction(function(tx) {
  tx.executeSql("SELECT * FROM test", [], successCallback, errorCallback);
});

    See the generated database: Developer > Developer Tools > Storage

    IndexedDB

    var db = indexedDB.open('books', 'Book store', false);
    if (db.version !== '1.0') {
      var olddb = indexedDB.open('books', 'Book store');
      olddb.createObjectStore('books', 'isbn');
      olddb.createIndex('BookAuthor', 'books', 'author', false);
      olddb.setVersion("1.0");
    }
    var index = db.openIndex('BookAuthor');
    var matching = index.get('fred');
    if (matching)
      report(matching.isbn, matching.name, matching.author);
    else
      report(null);

    The IndexedDB API implements a persistent (across browser/machine restarts) database that is quite stripped down. It is built upon "Object Stores" (btrees of key->value pairs) and Indexes (btrees of key->object store record). It includes an async API for use in pages and both an async and a sync API for workers.

    Application Cache API

    <html manifest="cache-manifest">
    window.applicationCache.addEventListener('checking', updateCacheStatus, false);
    
    CACHE MANIFEST
    
    # version 1
    
    CACHE:
    /html5/src/refresh.png
    /html5/src/logic.js
    /html5/src/style.css
    /html5/src/background.png
    

    Turn off your internet connection and refresh!

    Realtime Comunications

    • Server-Sent Event
    • Web Sockets
    • Geolocation

    Server-Sent Event

    var source = new EventSource('event.php');
    source.onmessage = function (event) {
      alert(event.data);
    };
    <?php
    header("Content-Type: text/event-stream");
        echo "data: " . time() . "\n";
    ?>

    Log console:

    Web Sockets

    var socket = new WebSocket(location);
    socket.onopen = function(event) {
      socket.postMessage(“Hello, WebSocket”);
    }
    socket.onmessage = function(event) { alert(event.data); }
    socket.onclose = function(event) { alert(“closed”); }

    Bi-directional, full-duplex communications channels, over a single Transmission Control Protocol (TCP) socket, designed to be implemented in web browsers and web servers.

    Geolocation

    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var lat = position.coords.latitude;
        var lng = position.coords.longitude;
        var options = { position: new google.maps.LatLng(lat, lng) }
        var marker = new google.maps.Marker(options);
        marker.setMap(map);
      });
    }
    

    Javascript API

    • New Media Elements
    • Desktop Experiences
    • Support Offlines
    • Realtime Comunications

    DEMO

    quake2-gwt-port

    When can I use HTML5?

    감사합니다.