로드중...

이 프리젠테이션은 HTML5 웹사이트입니다

키보드의 키를 누르면 다음 페이지로 이동합니다.

이 페이지는 오픈소스인 slides.html5rocks.com를 번역/수정한것입니다.

프리젠테이션을 보는데 문제가 있다면 disclaimer 를 읽어보세요

Slide 컨트롤 키:

  • 로 이동합니다.
  • Ctrl/Command+ 또는 - 로 확대/축소
  • T 키로 테마 변경
  • H 키로 syntax highlight 를 토글합니다.

HTML5*

Web Development to the next level

* 웹기술만으로 네이티브 애플리케이션 수준의 웹 애플리케이션을 개발

* Including other next generation technologies of the Web Development stack

Rough Timeline of Web Technologies
  • 1991 HTML
  • 1994 HTML 2
  • 1996 CSS 1 + JavaScript
  • 1997 HTML 4
  • 1998 CSS 2
  • 2000 XHTML 1
  • 2002 Tableless Web Design
  • 2005 AJAX
  • 2009 HTML 5
HTML Timeline
HTML5 ~= HTML + CSS + JS

Nuts & Bolts

Improvements to the core platform

JS

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 tds = document.querySelectorAll("table.test > tr > td");
var el = document.querySelector("table.test > tr > td"); // el == tds[0]
HTML JS

Custom data-* attributes

Define, store, and retrieve custom data on the DOM.

<div id="out" data-id="good" data-name="joe" data-screen-name="user1"></div>
// Add new data attributes via JS.
var el = document.querySelector('#out');
el.setAttribute('data-foo', 'bar');

var html = [];
for (var key in el.dataset) {
  html.push(key, ': ', el.dataset[key], '<br>');
}

el.innerHTML = html.join('');

Output:

id: good
name: joe
screenName: user1
foo: bar
JS

Element.classList

<div id="main" class="shadow rounded"></div>
var el = document.querySelector('#main').classList;
el.add('highlight');
el.remove('shadow');
el.toggle('highlight');

console.log(el.contains('highlight')); // false
console.log(el.contains('shadow')); // false
console.log(el.classList.toString() == el.className); // true

Output:

<div id="main" class="rounded"></div>

Offline / Storage

Expect the unexpected

JS

Web Storage

// localStorage 는 반 영구적으로 사용 ( 브라우저 재시작해도 남아있음 )
// sessionStorage 는 브라우저/탭이 닫히기 전까지만 사용
// 유효기간을 지정하지 않는것만 제외하면 쿠키와 비슷하게 동작
// 아래소스에서 localStorage 를 sessionStorage 로만 바로 바꿔서도 사용가능

textarea.addEventListener('keyup', function () {
  window.localStorage.setItem('value', area.value);
  window.localStorage.setItem('timestamp', (new Date()).getTime());
}, false);
textarea.value = window.localStorage.getItem('value');

사용 예제: 작성중인 이메일을 임시저장하기 (브라우저를 재시작하거나 다른 창을 띄워보세요)

JS

Web SQL Database

// 클라이언트 DB - Javascript DB API ( HTML5 표준스펙에선 제외 -> TechNotes )
// Insert , Update , Select , Delete , Transaction 지원

var db = window.openDatabase("DBName", "1.0", "description", 5*1024*1024); //5MB
db.transaction(function(tx) {
  tx.executeSql("SELECT * FROM test", [], successCallback, errorCallback);
});

// CREATE TABLE Table1Test (id REAL UNIQUE, text TEXT)
// INSERT INTO Table1Test (id, text) VALUES (?, ?)
// DELETE FROM Table1Test WHERE id=?

See the generated database: Developer > Developer Tools > Storage

    JS

    IndexedDB

    // 정식 DB 표준. 아직 구현된 브라우저가 많이 없음
    
    var idbRequest = window.indexedDB.open('Database Name');
    idbRequest.onsuccess = function(event) {
      var db = event.result;
      var transaction = db.transaction([], IDBTransaction.READ_ONLY);
      var curRequest = transaction.objectStore('ObjectStore Name').openCursor();
      curRequest.onsuccess = ...;
    };
    
    JS

    Application Cache

    <html manifest="cache.manifest">
    window.applicationCache.addEventListener('checking', updateCacheStatus, false);
    
    cache.manifest:
    CACHE MANIFEST
    
    # version 1
    
    CACHE:
    /html5/src/refresh.png
    /html5/src/logic.js
    /html5/src/style.css
    /html5/src/background.png
    
    첫번째 줄은 무조건 "CACHE MANIFEST" 라는 문자열을 포함해야한다. 
    각 라인은 캐시할 리소스의 URL 또는 주석을 포함한다.
    
    manifest 파일의 내용만으로 Refresh 여부를 판단. 각 파일의 내용이 바뀌었는지는 판단하지 않음.	
    text/cache-manifest MIME 타입으로 전송되어야 함.
    javascript event 를 통해 caching 진행여부를 알수 있음. 
    Window.applicationCache.update(); 및 swapCache(); 함수로 캐시를 강제로 업데이트 가능.
    

    Realtime / Communication

    Stay connected

    JS

    Web Workers

    main.js:
    var worker = new Worker('task.js');
    worker.onmessage = function(event) { alert(event.data); };
    worker.postMessage('data');
    
    task.js:
    self.onmessage = function(event) { 
      // 작업을 진행하고, 작업이 끝나면 postMessage 호출.
      self.postMessage("recv'd: " + event.data); 
    }; // 기본JS는 싱글쓰레드(setTimeout),Web Worker는 다중쓰레드,DOM접근불가 단순 계산용
    

    Loading Route...

    경로찾기 버튼을 누르고 맵을 드래그해보세요. (Workers를 사용할때만 가능합니다)

    JS

    WebSocket

    var socket = new WebSocket('ws://html5rocks.websocket.org/echo');
    socket.onopen = function(event) {
      socket.send('Hello, WebSocket');
    };
    socket.onmessage = function(event) { alert(event.data); }
    socket.onclose = function(event) { alert('closed'); }
    

    웹에서의 Full-duplex, bi-directional 통신:
    서버/클라이언트가 아무때나/동시에도 데이타 전송가능.
    HTTP 헤더없에 데이터만 전송되므로 네트워 트래픽이 효율적이다.

    Use the echo demo below to test a WebSocket connection from your browser. Both the message you send and the response you receive travel over the same WebSocket connection.

    Location:



    Message:

    Output:
    Demo powered by
    서버측은 따로 구현필요,기존 웹서버 확장/새로운 서비스들이 등장 (Node.js,phpwebsocket)
    
    Demo

    HTML5 Quake II - Web Sockets

    • WebSocket to support online Multiplayer
    • WebGL & Canvas , HTML Audio , Web Storage - Local Storage API
    • Jake2 (Java port of Quake2) is compiled to Javascript using GWT
    JS

    Notifications

    if (window.webkitNotifications.checkPermission() == 0) {
      // 아무 URL 이나 파라미터로 전달가능 
      window.webkitNotifications.createNotification(tweet.picture, tweet.title, 
          tweet.text).show();
    } else {
      window.webkitNotifications.requestPermission();
    }
    

    참고: 퍼미션을 리셋할때도 위 버튼을 사용하면 됩니다.


    트위터 ID 를 적으면, 마지막 트윗 3개를 notification 으로 보여줍니다

    createNotification 함수의 리턴값으로 popup 윈도우를 받아서 자동으로 사라지게도 가능.	
    
    현재 HTML5 의 표준에 들어있는것은 아님. draft spec 만 존재. 크롬만 지원.
    

    File / Hardware Access

    Deeper integration with the Operating System

    JS

    Native Drag & Drop

    document.addEventListener('dragstart', function(event) {
      event.dataTransfer.setData('text', 'Customized text');
      event.dataTransfer.effectAllowed = 'copy';
    }, false);
    
    1. 텍스트 선택후 드래그
      (원본텍스트 드롭)
    2. 텍스트 선택후 드래그
      (드롭된 텍스트가 원본과 다름)
    원본 데이타
    드롭 하는곳!

    이벤트 기반의 드래그 & 드롭 메커니즘
    드래그 가능하게 만들려면 - draggable 이라는 속성만 추가하면 됨 <img src='aa' draggable />
    drag , drop , dragstart , dragend , dragenter , dragleave , dragover 이벤트
    
    아이폰은 touchStart,touchEnd,touchMove,touchCancel 이벤트도 따로있음 (멀티터치 지원)
    gestureStart , gestureEnd , gestureChange 형태로 제스쳐도 지원.
    
    JS

    Desktop Drag-In (File API)

    데스크탑으로부터 파일 드래그 하기:

    document.querySelector('#dropzone').addEventListener('drop', function(e) {
      var reader = new FileReader();
      reader.onload = function(evt) {
        document.querySelector('img').src = evt.target.result;
      };
    
      reader.readAsDataURL(evt.dataTransfer.files[0]);
    }, false);
    
    데스크탑에 있는 이미지 파일을 Drop 해주세요
    JS

    Desktop Drag-Out

    데스크탑으로 파일 드래그 하기:

    <a href="src/star.mp3" draggable="true" class="dragout"
       data-downloadurl="MIMETYPE:FILENAME:ABSOLUTE_URI_TO_FILE">download</a>
    
    var files = document.querySelectorAll('.dragout');
    for (var i = 0, file; file = files[i]; ++i) {
      file.addEventListener('dragstart', function(e) {
        e.dataTransfer.setData('DownloadURL', this.dataset.downloadurl);
      }, false);
    }
    
    각 파일을 데스크탑으로 드래그 해보세요: .pdf file .mp3 file

    ( 이 기능은 Google Chrome 에서만 가능합니다 )

    JS

    Geolocation

    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var latLng = new google.maps.LatLng(
            position.coords.latitude, position.coords.longitude);
        var marker = new google.maps.Marker({position: latLng, map: map});
        map.setCenter(latLng);
      }, errorHandler);
    }
    
    JS

    Device Orientation

    window.addEventListener('deviceorientation', function(event) {
      var a = event.alpha;
      var b = event.beta;
      var g = event.gamma;
    });
    
    HTML

    Speech Input

    <input type="text" x-webkit-speech />

    Semantics & Markup

    More meaningful elements

    HTML

    New Semantic Tags

    HTML4 HTML5

    구글이 2005년에 10억개 이상의 웹페이지를 분석한 결과 가장 많이 쓰는 클래스 이름 20개

    유명(?) Class 대응되는
    HTML5 Element
    footer footer
    menu menu
    title, header, top (?) header
    small, smalltext small
    text, content, main, body article
    nav nav
    copyright none yet
    button IE6 의 제한
    search none yet
    date date
    link ?
    HTML

    Better semantic tags

    <body>
      <header>
        <hgroup>
          <h1>Page title</h1>
          <h2>Page subtitle</h2>
        </hgroup>
      </header>
    
      <nav>
       <ul>
         Navigation...
       </ul>
      </nav>
      <section>
       <article>
         <header>
           <h1>Title</h1>
         </header>
         <section>
           Content...
         </section>
       </article>
       <article>
         <header>
           <h1>Title</h1>
         </header>
         <section>
           Content...
         </section>
       </article>
      </section>
    
      <aside>
       Top links...
      </aside>
    
      <figure>
        <img src="..."/>
        <figcaption>Chart 1.1</figcaption>
      </figure>
    
      <footer>
       Copyright ©
    <time datetime="2010-11-08">2010</time>. </footer> </body>
    HTML

    Markup for applications

    <input list="cars"/>
    <datalist id="cars">
      <option value="BMW"/>
      <option value="Ford"/>
      <option value="Volvo"/>
    </datalist>
    
    <menu>
      <command type="command">Click Me!</command>
    </menu>
    
    <details>
      <summary>HTML 5</summary>
      This slide deck teaches you everything you need to know about HTML 5.
    </details>
    
    <meter min="0" max="100" low="40" high="90" optimum="100" value="91">A+</meter>
    Your score is: A+
    <progress>working...</progress> Download is: working...
    <progress value="75" max="100">3/4 complete</progress> Goal is: 3/4 complete
    HTML

    Microdata

    <div itemscope itemtype="http://example.org/band">
     <p>My name is <span itemprop="name">Neil</span>.</p>
     <p>My band is called <span itemprop="band">Four Parts Water</span>.</p>
     <p>I am <span itemprop="nationality">British</span>.</p>
    </div>
    
    	구글 검색엔진이 인식하는 Microdata 스펙 http://www.data-vocabulary.org/
    	Event , Organization , Person , Product , Review
    
    HTML

    ARIA attributes

    <ul id="tree1"
          role="tree" 
          tabindex="0" 
          aria-labelledby="label_1">
      <li role="treeitem" tabindex="-1" aria-expanded="true">Fruits</li>
      <li role="group">
        <ul>
          <li role="treeitem" tabindex="-1">Oranges</li>
          <li role="treeitem" tabindex="-1">Pineapples</li>
          ...
        </ul>
      </li>
    </ul>
    
    ARIA : Accessible Rich Internet Applications
    
    HTML

    New form types

    <style>
      :invalid { 
        border-color: #e88;
        -webkit-box-shadow: 0 0 5px rgba(255, 0, 0, .8);
      }
      [required] {
        border-color: #88a;
        -webkit-box-shadow: 0 0 3px rgba(0, 0, 255, .5);
      }
    </style>
    
    <input type="text" required />
    <input type="email" value="some@email.com" /> 
    <input type="date" min="2010-08-14" max="2011-08-14" value="2010-08-14"/> 
    <input type="range" min="0" max="50" value="10" /> 
    <input type="search" results="10" placeholder="Search..." /> 
    <input type="tel" placeholder="(555) 555-5555" pattern="^\(?\d{3}\)?[-\s]\d{3}[-\s]\d{4}.*?$" />
    
    <input type="color" placeholder="e.g. #bbbbbb" /> 
    <input type="number" step="1" min="-5" max="10" value="0" /> 
    

    Graphics / Multimedia

    2D & 3D

    HTML JS

    Audio + Video

    <audio id="audio" src="sound.mp3" controls></audio>
    document.getElementById("audio").muted = false;
    
    <video id="video" src="movie.webm" autoplay controls></video>
    document.getElementById("video").play();
    
    HTML JS

    Canvas 2D

    <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>
                
    HTML JS

    Canvas example

    HTML JS

    Canvas 3D (WebGL)

    <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>
                
    HTML

    Inline SVG

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

    SVG example

    CSS3

    Presentation & Styling

    CSS

    CSS Selectors

    Selectors

    .row:nth-child(even) {
      background: #dde;
    }
    .row:nth-child(odd) {
      background: white;
    }
    
    Row 1
    Row 2
    Row 3
    Row 4

    Image-like display

    div {
      display: inline-block;
    }
    

    Specific attributes

    input[type="text"] {
      background: #eee;
    }

    Negation

    :not(.box) {
      color: #00c; 
    }            
    :not(span) {
      display: block; 
    }  
    

    More specific targetting

    h2:first-child { ... }
    
    div.text > div { ... } 
    h2 + header { ... } 
    
    CSS

    Webfonts

    @font-face {
      font-family: 'LeagueGothic';
      src: url(LeagueGothic.otf);
    }
    
    @font-face {  font-family: 'Droid Sans';  src: url(Droid_Sans.ttf); }
    
    header {
      font-family: 'LeagueGothic';
    }
    LeagueGothic font with no image replacement
    구글이 Font API , Web Font LoaderFont Directory 를 공개했음 @Google I/O 2010
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Tangerine">
     .gfont { font-family: 'Tangerine';font-size: 64px;text-shadow: 4px 4px 4px #aaa;}
    <span class=gfont>Making the Web Beautiful</span>
    Making the Web Beautiful.
    CSS

    Text wrapping

    div {
      text-overflow: ellipsis;
    }
    A long cold winter delayed the blossoming of the millions of cherry, apricot, peach, and prune plum trees covering hundreds of square miles of the Valley floor. Then, unlike many years, the rains that followed were light and too early to knock the blossoms from their branches.
    A long cold winter delayed the blossoming of the millions of cherry, apricot, peach, and prune plum trees covering hundreds of square miles of the Valley floor. Then, unlike many years, the rains that followed were light and too early to knock the blossoms from their branches.
    A long cold winter delayed the blossoming of the millions of cherry, apricot, peach, and prune plum trees covering hundreds of square miles of the Valley floor. Then, unlike many years, the rains that followed were light and too early to knock the blossoms from their branches.

    Play with the slider on this and further pages!

    CSS

    Columns

    -webkit-column-count: 2; 
    -webkit-column-rule: 1px solid #bbb;
    -webkit-column-gap: 2em;

    In March 1936, an unusual confluence of forces occurred in Santa Clara County.

    A long cold winter delayed the blossoming of the millions of cherry, apricot, peach, and prune plum trees covering hundreds of square miles of the Valley floor. Then, unlike many years, the rains that followed were light and too early to knock the blossoms from their branches.

    Instead, by the billions, they all burst open at once. Seemingly overnight, the ocean of green that was the Valley turned into a low, soft, dizzyingly perfumed cloud of pink and white. Uncounted bees and yellow jackets, newly born, raced out of their hives and holes, overwhelmed by this impossible banquet.

    Then came the wind.

    It roared off the Pacific Ocean, through the nearly uninhabited passes of the Santa Cruz Mountains and then, flattening out, poured down into the great alluvial plains of the Valley. A tidal bore of warm air, it tore along the columns of trees, ripped the blossoms apart and carried them off in a fluttering flood of petals like foam rolling up a beach.

    This perfumed blizzard hit Stevens Creek Boulevard, a two-lane road with a streetcar line down its center, that was the main road in the West Valley. It froze traffic, as drivers found themselves lost in a soft, muted whiteout. Only the streetcar, its path predetermined, passed on...

    CSS

    Text stroke

    div {
      -webkit-text-fill-color: black;
      -webkit-text-stroke-color: red;
      -webkit-text-stroke-width: 0.00px; 
    }
    Text stroke example
    CSS

    Opacity

      color: rgba(255, 0, 0, 0.75); 
      background: rgba(0, 0, 255, 0.75); 
    
    Independent opacity
    CSS

    Hue/saturation/luminance color

    color: hsla(
      128 
      74% 
      33% 
      1.00 
            
    HSL example
    CSS

    Rounded corners

      border-radius: 0px; 
    
    Example
    CSS

    Gradients

    background: -webkit-gradient(linear, left top, left bottom, 
                                 from(#00abeb), to(white), 
                                 color-stop(0.5, white), color-stop(0.5, #66cc00))
    

    background: -webkit-gradient(radial, 430 50, 0, 430 50, 200, from(red), to(#000))
                                                            
    
    CSS

    Shadows

    text-shadow: 
      rgba(64, 64, 64, 0.5) 
      0px 
      0px 
      0px; 
    
    box-shadow: rgba(0, 0, 128, 0.25) 0px 0px 0px;
    Shadows example
    CSS

    Instant Web 2.0 (just add sliders)

    text-shadow: rgba(0, 0, 0, 0.5) 0 0px 0px; 
    
    background: 
      -webkit-gradient(linear, left top, left bottom, 
                       from(rgba(200, 200, 240, 0)), to(rgba(255, 255, 255, 0)));
    
    border-radius: 0px; 
    
    -webkit-box-reflect: below 10px
      -webkit-gradient(linear, left top, left bottom, 
                       from(transparent), to(rgba(255, 255, 255, 0)));
    
    Web 2.0 Logo Creatr
    CSS

    Background enhancements

    Background sizing

    #logo {
      background: url(logo.gif) center center no-repeat;
      background-size: 
        ;
    }
    

    Resize me! »

    Multiple backgrounds

    div {
      background: url(src/zippy-plus.png) 10px center no-repeat, 
                  url(src/gray_lines_bg.png) 10px center repeat-x;
    }
                
    Test
    CSS

    Flexible Box Model

    .box {
      display: -webkit-box;
      -webkit-box-orient: ;
    }
    .box .one, .box .two {
      -webkit-box-flex: 1;
    }
    .box .three {
      -webkit-box-flex: 3;
    }
    
    Box one
    Box two
    Box three
    CSS

    Flexible Box Model

    .box {
        display: -webkit-box;
        -webkit-box-pack: ;
        -webkit-box-align: ;
      }
    
    CSS

    Transitions

    #box.left {
      margin-left: 0;
    }
    #box.right {
      margin-left: 1000px;
    }
    
    document.getElementById('box').className = 'left'; 
    document.getElementById('box').className = 'right'; 
    
    #box {
      -webkit-transition: margin-left 1s ease-in-out;
    }
    
    document.getElementById('box').className = 'left'; 
    document.getElementById('box').className = 'right'; 
    
    CSS

    Transforms

    Hover over me:

    -webkit-transform: rotateY(45deg);
    -webkit-transform: scaleX(25deg);
    -webkit-transform: translate3d(0, 0, 90deg);
    -webkit-transform: perspective(500px)
    
    #threed-example {
      -webkit-transform: rotateZ(5deg);
    
      -webkit-transition: -webkit-transform 2s ease-in-out;
    }
    #threed-example:hover {
      -webkit-transform: rotateZ(-5deg);
    }
    

    Now press 3!

    CSS

    Animations

    @-webkit-keyframes pulse {
     from {
       opacity: 0.0;
       font-size: 100%;
     }
     to {
       opacity: 1.0;
       font-size: 200%;
     }
    }
    
    div {
      -webkit-animation-name: pulse;
      -webkit-animation-duration: 2s;
      -webkit-animation-iteration-count: infinite;
      -webkit-animation-timing-function: ease-in-out;
      -webkit-animation-direction: alternate;
    }
    

    *Please make a better use of it. We don't want a new blink tag ;)

    Pulse!

    See it today?

    • Modern Browsers
    • Mobile Browsers
    • Chrome extensions/Firefox Jetpack/Safari extensions

    Chrome Frame

    • Minimal effort for bringing IE6, 7 and 8 up to the latest HTML5 technologies
    • Two ways to get your websites ready for Chrome Frame:

    Client side:

    <meta http-equiv="X-UA-Compatible" content="chrome=1">

    Server side:

    X-UA-Compatible: chrome=1

    Try to load this presentation in IE!

    HTML5 ~= HTML + CSS + JS

    HTML5 = Next Generation Features for Modern Web Development