SlideShare a Scribd company logo
HTML5 Mobile APIs
                  Use Mobile Device Capabilities
                  From The Browser
Tuesday, September 18, 12
Web Tech History
                  1991 HTML

                  1994 HTML2

                  1996 CSS1 + JavaScript

                  1997 HTML4

                  1998 CSS2

                  2000 XHTML1

                  2002 Tableless Web Design

                  2005 Ajax

                  2009 HTML5




Tuesday, September 18, 12
HTML5 What


                  Syntactical Features (audio, video)

                  Semantical Features (section, article)

                  New APIs




Tuesday, September 18, 12
HTML5 How

                  Progressive Enhancements

                  Existing web sites can move to HTML5

                  Old browsers will still be able to use the page

                  Modernizr: http://www.modernizr.com/




Tuesday, September 18, 12
HTML5 New APIs
                  Web Storage            Geolocation

                  Web SQL                Device Orientation

                  Application Cache      Form Enhancements

                  Web Workers            Audio, Video

                  Web Socket             Canvas

                  Desktop Notifications   Web GL

                  Drag & Drop            History API

                  File System API        And More...



Tuesday, September 18, 12
HTML5 Mobile Related
                  APIs

                  Storage

                  Geo Location

                  Video

                  Canvas




Tuesday, September 18, 12
Offline Storage




                   Work Offline   Store Persistent State




Tuesday, September 18, 12
Local Data Storage


                  How do you store data on a client’s machine ?




Tuesday, September 18, 12
Cookies ?




Tuesday, September 18, 12
Local Storage
                  Before HTML5: cookies were used to store data
                  on the client side

                  Cookies Disadvantages:

                        Limited size (4k)

                        Sent with every request

                        Complex to use



Tuesday, September 18, 12
Local Storage
                  A JavaScript API for
                  storing client side data

                  Can store up to 5MB
                  (per site)

                  Simple API

                  Never run out of space



Tuesday, September 18, 12
Local Storage

                  Store Data
                  window.localStorage.setItem(“key”, “value”);


                  Read Data
                  window.localStorage.getItem(“key”);


                  Remove Data
                  window.localStorage.removeItem(“key”);




Tuesday, September 18, 12
Check Status

                  Can check if online using:

                  navigator.onLine


                  Relevant events: online, offline

                  Listen with:
                  document.addEventListener(‘online’, ... );




Tuesday, September 18, 12
Local Storage

                  Can also use direct access on the storage object,
                  so this code also works:

                  window.localStorage.username = “Jimmy”;
                  var username = window.localStorage.username;

                  console.log(‘Hello ‘ + username);




Tuesday, September 18, 12
Local Storage

                  Use clear() to delete all objects in the cache
                  related to this page


                  Use key() to get an item by its index (for
                  example, to iterate all keys)




Tuesday, September 18, 12
Session Storage

                  Interface is the same as localStorage

                  Lifetime is only for the current browser window or
                  tab (or browser session)

                  Best used for temporary preferences that should
                  not be shared between tabs




Tuesday, September 18, 12
Storage Example

                  We’ll implement an address book app

                  Keeps a list of contacts info: name, phone number,
                  email

                  Provide add/view/delete contacts




Tuesday, September 18, 12
Address Book

                  examples/html5/contacts




Tuesday, September 18, 12
Exercise (1/2)

                  Implement a todo list mini-app

                  Use a single form to add tasks

                  Use local storage to store them

                  Display a list of active tasks




Tuesday, September 18, 12
Exercise (2/2)
                  Use jQM to get a native look

                  App should display a list of all active tasks

                  Header button called “Add” should open a popup
                  with new task description, and buttons to “Save”
                  or “Abort”

                  Bonus: Swipe to delete



Tuesday, September 18, 12
Offline Web App

                  Online-Offline Apps

                  Sync with the Cloud, but can suffer a downtime
                  (Think Google Gears)

                  Can run completely offline app as a standalone

                  Mobile - Save bandwidth




Tuesday, September 18, 12
Offline Web App
                             GET MANIFEST


                            CACHE MANIFEST
                            index.html
                            style/main.css
                            script/main.js




Tuesday, September 18, 12
Cache Manifest File


                  Lists all the files that should be stored for offline
                  access

                  Enable with:
                  <html manifest="example.appcache">




Tuesday, September 18, 12
example.appcache

                                          CACHE MANIFEST
                  Required header
                                          index.html
                  CACHE MANIFEST
                                          stylesheet.css
                  A list of cached files
                                          images/logo.png

                                          scripts/main.js




Tuesday, September 18, 12
Demo
             Caching A Website




Tuesday, September 18, 12
Offline Web App

                  The cache manifest is divided to sections, the
                  default is called CACHE

                  Every file listed in the default CACHE section will
                  be cached by the browser forever (or until
                  explicitly deleted by the user)




Tuesday, September 18, 12
Offline Web App


                  The NETWORK section lists files that should never
                  be cached

                  Best used for dynamic content (think gmail)




Tuesday, September 18, 12
Offline Web App

                  The FALLBACK section lists fallback content that
                  should be used if network is not available

                  So, if you’re trying to read a message while offline,
                  you can get a nice formatted error page




Tuesday, September 18, 12
Manifest Cache

                                       Cache the file locally,
                            CACHE
                                       never refresh


                                       Files should not be
                            NETWORK
                                       cached


                                       Cache a fallback
                            FALLBACK
                                       content



Tuesday, September 18, 12
Offline App Exercise

                  A Dynamic reader with two pages

                  First lists available articles, the second displays a
                  given article

                  Use your favorite server side technology and jQM

                  Which files do you put in each manifest section ?




Tuesday, September 18, 12
Manifest - The Good

                  Can store any file
                  locally

                  Provides offline/online
                  app functionality

                  Transparent to the user




Tuesday, September 18, 12
Manifest - The Bad


                  Not suitable for data
                  storage

                  Complex update logic




Tuesday, September 18, 12
Web SQL

                  The final storage option for offline apps is the Web
                  SQL

                  Allows using a local database to better store
                  relational data

                  Best suited for hierarchical lists apps




Tuesday, September 18, 12
Q&A

                  Storage

                  Geo Location

                  Video

                  Canvas




Tuesday, September 18, 12
Geo Location

                  Detect where your user
                  is now

                  Show nearby places

                  Display location aware
                  data




Tuesday, September 18, 12
Technologies

                  GPS

                  A-GPS

                  Cell Information

                  WiFi Positioning




Tuesday, September 18, 12
GPS
                  Global Positioning
                  System

                  Accuracy error: 2-10m

                  Requires clear sky view

                  Time to position:
                  5 seconds - 5 minutes



Tuesday, September 18, 12
A-GPS

                  Uses both GPS chip
                  and network
                  information to get
                  location

                  Much faster to get
                  location




Tuesday, September 18, 12
Cell Information
                  Uses cell towers to
                  calculate a device’s
                  location

                  Accuracy: A block or
                  up to some km

                  Time to location:
                  immediate



Tuesday, September 18, 12
WiFi Positioning

                  Detect location using a
                  list of wireless routers
                  in your area

                  Relies on existing
                  router databases




Tuesday, September 18, 12
Location API


                  Supported Platforms:

                        iPhone 3.0+

                        Android 2.0+




Tuesday, September 18, 12
Location API

                  function get_location() {
                    navigator.geolocation.getCurrentPosition(show_map);
                  }

                  function show_map(position) {
                    var lat = position.coords.latitude;
                    var long = position.coords.longitude;
                    var when = position.timestamp;
                    // show me the map
                  }




Tuesday, September 18, 12
Location API

                  navigator.geolocation is the entry point for
                  all location related calls

                  Location querying is async, so a callback is
                  supplied

                  User will be asked permission to share location




Tuesday, September 18, 12
Location API


                  iPhone browser asks
                  user permissions
                  before sharing location




Tuesday, September 18, 12
Location API

                  Location API uses
                  callbacks to perform
                  error handling

                  When working with
                  location, always
                  consider errors




Tuesday, September 18, 12
Location API

                   getCurrentPosition(

                            successCallback,

                            optional errorCallback,

                            optional config

                   );




Tuesday, September 18, 12
The Coord object
                  coords.latitude

                  coords.longitude

                  coords.altitude

                  coords.accuracy

                  coords.altitudeAccuracy

                  coords.heading

                  coords.speed

                  timestamp




Tuesday, September 18, 12
The Coord Object

                  Not all fields will be available at all times

                  Sizes are specified in meters and degrees

                  timestamp is a DOMTimestamp (acts like a Date
                  object)




Tuesday, September 18, 12
Location Config
                  last parameter to getCurrentPosition is a config
                  object

                  there are 3 configuration options available:

                        timeout

                        maximumAge

                        enableHighAccuracy



Tuesday, September 18, 12
Using Config

                   window.navigator.geolocation.getCurrentPosition(
                     successCallback,
                     failureCallback,
                                                             How long to wait before giving up
                       { timeout               : 0,                      (in ms)


                            maximumAge         : 60000,       Try to use a cached value aged
                                                                           (in ms)


                            enableHighAccuracy : false });        Use the most accurate
                                                                   positioning method




Tuesday, September 18, 12
Handle Errors

                  The errorCallback takes a single argument called
                  error object

                  The object has two fields:
                  error.code & error.message

                  Use error.message for debug only




Tuesday, September 18, 12
Next: The Map




Tuesday, September 18, 12
Show The Map

                  On the iPhone, a redirect to a google maps url
                  starts the map application

                  The Good: easy to use

                  The Bad:

                        user leaves the app




Tuesday, September 18, 12
Google Maps API

                  A JS API to display
                  embedded maps in
                  web sites

                  Works on both desktop
                  and mobile devices

                  Free to use




Tuesday, September 18, 12
Google Maps API
                  Assign a special empty div that will contain the
                  map. recommended size of the div is entire page.

                  Display the map by creating a google.maps.Map
                  object

                  Place markers on the map using
                  google.maps.Marker

                  Full documentation:
                  http://code.google.com/apis/maps/
                  documentation/javascript/
Tuesday, September 18, 12
Demo
             Show Location On Map




Tuesday, September 18, 12
Location Tracking


                  Receive notifications about location changes

                  Can use for navigation apps, sport apps, and more

                  Browser must remain open




Tuesday, September 18, 12
Location Tracking

                     use watchPosition to start watching a user’s
                     position

                     The method returns a watch id. Keep it. When
                     tracking is no longer needed, use clearWatch
                     with the watch id to stop.

                     The callback of watchPosition will get called
                     every time location has changed


Tuesday, September 18, 12
Exercise: Where’s My
                  Car
                  Write a parking reminder app

                  One button titled “parked” which marks current
                  location and keeps it in local storage

                  Another button titled “find” which shows a map
                  leading to your car

                  Keep data in local storage



Tuesday, September 18, 12
Q&A

                  Storage

                  Geo Location (iPhone, Android)

                  Video (iPhone, Android)

                  Canvas (iPhone, Android)




Tuesday, September 18, 12
VIDEO
    THE EASY WAY
Tuesday, September 18, 12
Video Tag

                        HTML5 introduces a <video> tag to embed
                        videos in a web page.

                        Different browsers support different video
                        formats. The <video> tag can specify multiple
                        formats.




Tuesday, September 18, 12
Video Formats
                  Video formats are like
                  languages

                  The same video can be
                  encoded in different
                  formats

                  A browser must “speak
                  the language” to be
                  able to play the video


Tuesday, September 18, 12
Browser Support


                  HTML5 spec does not define a video codec to use

                  h.264 is the most widely supported. Plays on
                  iPhone and Android




Tuesday, September 18, 12
The Markup

                                             Poster image file name

                   <video poster=”star.png”>

                            <source src=”zebra.mp4” />
                                           Video file name. Usually mp4
                   </video>                     for mobile devices




Tuesday, September 18, 12
Limitations

                  Video will start playing in a dedicated “player”
                  window, when the user taps it

                  It is not possible to auto play the video on mobile

                  It is not possible to embed other content on the
                  video on mobile




Tuesday, September 18, 12
Q&A

                  Storage

                  Geo Location

                  Video

                  Canvas (iPhone, Android)




Tuesday, September 18, 12
CANVAS
Tuesday, September 18, 12
HTML5 Canvas
                  A 2d graphics canvas
                  for HTML apps

                  Games

                  Dynamic images

                  Client-side painting
                  (saves bandwidth)



Tuesday, September 18, 12
Hello Canvas


                  An HTML element <canvas> on the markup

                  JS code to do actual painting




Tuesday, September 18, 12
Hello Canvas

                  The canvas element has no content and no border
                  of its own

                  A canvas keeps a painting context on which we
                  perform the drawing

                  First example uses context.fillText()

                            examples/canvas/intro.html




Tuesday, September 18, 12
Basic Drawing

                  Context object provides the drawing functions.
                  Each takes coordinates and data.

                  Drawing style is determined by setting attributes
                  on the context object.

                  Most style properties are plain text strings




Tuesday, September 18, 12
Coordinate System




Tuesday, September 18, 12
Drawing Rectangles
                  Let’s start with drawing
                  rectangles                 fillRect(x, y, w, h)

                  note fillRect draws a       strokeRect(x, y, w, h)

                  filled rectangle, while     clearRect(x, y, w, h)
                  strokeRect draws just
                  the outline

                  fillStyle and strokeStyle
                  determine the colors


Tuesday, September 18, 12
Demo: Rects



Tuesday, September 18, 12
Drawing Paths

                  A composite shape on the canvas is called “path”

                  Paths are made of lines, arcs, curves and
                  rectangles

                  A path can be filled or stoked. Nothing is painted
                  until either fill() or stroke() is called




Tuesday, September 18, 12
Drawing Paths

                                           moveTo(x, y)
                  Lines are painted with
                  lineTo and moveTo        lineTo(x, y)

                  stroke() performs the
                  actual drawing




Tuesday, September 18, 12
Lines Example

          ctx.beginPath();
          ctx.strokeStyle = "hsl(249, 41%, 50%)";

          ctx.lineWidth = 6;
          ctx.moveTo(0, 0);
          ctx.lineTo(20, 10);
          ctx.lineTo(0, 20);
          ctx.stroke();




         Cool Color Selector:
         http://mothereffinghsl.com/

Tuesday, September 18, 12
Using The Image

                  It’s possible to use an image drawn in a canvas for
                  other elements

                  get the image url using:
                  canvas.toDataURL()

                  use image url as a source attribute of an img tag

                  Extra: draw on a hidden canvas



Tuesday, September 18, 12
Drawing Circles
                  use arc() and arcTo() to   arc(x, y, radius,
                  draw circles or parts of       startAngle,
                  them                           endAngle,
                                                 antiClockWise)
                  Degrees are specified
                  in radians.                arcTo(x1, y1,
                  Math.PI = 180 deg                x2, y2,
                                                   radius)
                  remember to fill() or
                  stroke()


Tuesday, September 18, 12
Exercise 1

                  Draw the image on the
                  right

                  Use moveTo and arc

                  Bonus: add colors




Tuesday, September 18, 12
Exercise 2

                  Draw the image on the
                  right

                  Place pins randomly
                  across the screen




Tuesday, September 18, 12
Advanced Canvas


                  Transformations

                  Image Filters




Tuesday, September 18, 12
Transformations

                  supported               translate(x, y)
                  transformations:
                  translation, scaling,   rotate(angle)
                  rotation                scale(x, y)
                  Transformations affect
                  all drawing code
                  performed after them




Tuesday, September 18, 12
Translation

                  Move the origin of the canvas to another point on
                  the canvas

                  The new point is now (0, 0)

                  This can make drawing code simpler




Tuesday, September 18, 12
Translation Example


                  Use translation to paint
                  the four painted
                  rectangles on the right




                       examples/html5/canvas/translate.html

Tuesday, September 18, 12
Scaling


                  scales the rendering context size

                  x and y are scale factors

                  translate before scale to maintain position




Tuesday, September 18, 12
Scale Example




                                  examples/html5/canvas/scale.html

Tuesday, September 18, 12
Rotation

                  Rotates a shape around its (0, 0) point of origin

                  Angle is specified in radians.
                  Math.PI     = 180 deg (half a circle)
                  Math.PI / 4 = 45 deg

                  Translate before rotate to maintain position




Tuesday, September 18, 12
Example: Rotation
         ctx.translate(75,75);

         for (var i=1;i<6;i++){
           ctx.save();
           ctx.fillStyle = 'rgb('+(51*i)+','+(255-51*i)+',255)';

             for (var j=0;j<i*6;j++){ // draw individual dots
               ctx.rotate(Math.PI*2/(i*6));
               ctx.beginPath();
               ctx.arc(0,i*12.5,5,0,Math.PI*2,true);
               ctx.fill();
             }

             ctx.restore();
         }




Tuesday, September 18, 12
Example: Rotation
                  The background was
                  painted with a gradient   ctx.save();

                  fill                       var grad = ctx.createLinearGradient(0, 0,
                                            150, 0);
                                            grad.addColorStop(0, "#888");
                                            grad.addColorStop(1, "#eee");
                  Notice the save() and     ctx.fillStyle = grad;
                  restore() at the          ctx.fillRect(0, 0, 150, 150);
                                            ctx.fill();

                  beginning and end.        ctx.restore();


                  Now we can put the
                  code inside a function,
                  and it won’t affect
                  outside code

Tuesday, September 18, 12
Exercise

                  Draw the clock on the
                  right

                  Use rotate to simplify
                  calculations

                  Bonus: Show the time




Tuesday, September 18, 12
Image Filters




Tuesday, September 18, 12
Drawing Images on
                  Canvas
                  It’s possible to paint a png or jpeg image on a
                  canvas using drawImage

                  Canvas also lets JS code take the pixels from the
                  image into an array. Using this array, we can
                  transform the pixels and write the result to a new
                  canvas

                  The operation is called filtering



Tuesday, September 18, 12
Image Drawing API

                 drawImage(image, x, y)
                 paint an entire image object on the canvas at position (x,y)



                 drawImage(image, x, y, w, h)
                 paint an entire image object on the canvas, scaling it to size (w,h)



                 drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
                 paint a slice of the image on a canvas, can use dw,dh to scale




Tuesday, September 18, 12
Image Filters

                     For the next few slides, we’ll create a Filters
                     object. Each filter is a function of that Filters
                     object

                     The Filters object is responsible for reading pixel
                     data and interacting with the canvas

                     A filter function takes pixel data and
                     manipulates it


Tuesday, September 18, 12
Filters Code

                     When testing on
                     desktop, some                       canvas.toDataURL()
                     browsers will throw                 ctx.getImageData(sx, sy, sw, sh)
                     security exceptions if              ctx.putImageData(data, dx, dy)
                     the page is read locally.

                     Code:
                     examples/html5/canvas/filters.html




Tuesday, September 18, 12
Canvas Exercise
                  Implement a mobile drawing app using the canvas
                  and touch events

                  App should have a footer with a selection of
                  colors. Tapping a color sets current color

                  Tapping anywhere on screen should draw in the
                  selected color

                  Bonus: share photo on server



Tuesday, September 18, 12
Q&A
Tuesday, September 18, 12
Thank You


                  Ynon Perek

                  ynonperek@yahoo.com

                  ynonperek.com




Tuesday, September 18, 12

More Related Content

PDF
07 PhoneGap
PDF
Html5 apis
PDF
When Smalltalk Meets the Web
PPTX
CDNs para el SharePoint Framework (SPFx)
PDF
XPages Blast - Lotusphere 2013
PPTX
How to Create a Drupal 8 Theme Using Bootstrap
PDF
Crx 2.2 Deep-Dive
PDF
soft-shake.ch - Windows Phone 7 „Mango“ – what’s new for Developers?
07 PhoneGap
Html5 apis
When Smalltalk Meets the Web
CDNs para el SharePoint Framework (SPFx)
XPages Blast - Lotusphere 2013
How to Create a Drupal 8 Theme Using Bootstrap
Crx 2.2 Deep-Dive
soft-shake.ch - Windows Phone 7 „Mango“ – what’s new for Developers?

Similar to 06 HTML5 Mobile (20)

PDF
Front-end optimisation & jQuery Internals
PPT
Persistent Offline Storage White
PDF
01 Mobile Web Introduction
PPTX
Asp.net performance
PDF
More efficient, usable web
PDF
Gatsby (Code.Talks) 2019
PDF
Drupal 8 Render Cache
PPTX
Local storage
PDF
Logical-DataWarehouse-Alluxio-meetup
PDF
Building an Apache Sling Rendering Farm
PPT
High Performance Web Pages - 20 new best practices
PPTX
Tips and tricks in the OSGi Web Console
PDF
your browser, my storage
PDF
WordPress: Performance Optimization and Scaling - WordCamp Las Vegas 2011
PPTX
The life in the Cloud
PDF
Creating Data Driven HTML5 Applications
PPTX
Microsoft Windows Server AppFabric
PPTX
PDF
Front-end optimisation & jQuery Internals (Pycon)
PPTX
The War on ActionView with Russian Doll Caching
Front-end optimisation & jQuery Internals
Persistent Offline Storage White
01 Mobile Web Introduction
Asp.net performance
More efficient, usable web
Gatsby (Code.Talks) 2019
Drupal 8 Render Cache
Local storage
Logical-DataWarehouse-Alluxio-meetup
Building an Apache Sling Rendering Farm
High Performance Web Pages - 20 new best practices
Tips and tricks in the OSGi Web Console
your browser, my storage
WordPress: Performance Optimization and Scaling - WordCamp Las Vegas 2011
The life in the Cloud
Creating Data Driven HTML5 Applications
Microsoft Windows Server AppFabric
Front-end optimisation & jQuery Internals (Pycon)
The War on ActionView with Russian Doll Caching
Ad

More from Ynon Perek (20)

PDF
Regexp
PDF
Html5 intro
PDF
09 performance
PDF
Mobile Web Intro
PDF
Qt multi threads
PDF
Vimperl
PDF
Syllabus
PDF
Mobile Devices
PDF
Network
PDF
Architecture app
PDF
Cryptography
PDF
Unit Testing JavaScript Applications
PDF
How to write easy-to-test JavaScript
PDF
Introduction to Selenium and Ruby
PDF
Introduction To Web Application Testing
PDF
Accessibility
PDF
Angularjs
PDF
Js memory
PDF
Qt Design Patterns
PDF
Web Application Security
Regexp
Html5 intro
09 performance
Mobile Web Intro
Qt multi threads
Vimperl
Syllabus
Mobile Devices
Network
Architecture app
Cryptography
Unit Testing JavaScript Applications
How to write easy-to-test JavaScript
Introduction to Selenium and Ruby
Introduction To Web Application Testing
Accessibility
Angularjs
Js memory
Qt Design Patterns
Web Application Security
Ad

Recently uploaded (20)

PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Big Data Technologies - Introduction.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Empathic Computing: Creating Shared Understanding
PDF
Encapsulation theory and applications.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
Cloud computing and distributed systems.
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
Unlocking AI with Model Context Protocol (MCP)
Big Data Technologies - Introduction.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Empathic Computing: Creating Shared Understanding
Encapsulation theory and applications.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Review of recent advances in non-invasive hemoglobin estimation
“AI and Expert System Decision Support & Business Intelligence Systems”
The AUB Centre for AI in Media Proposal.docx
Encapsulation_ Review paper, used for researhc scholars
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
Per capita expenditure prediction using model stacking based on satellite ima...
Programs and apps: productivity, graphics, security and other tools
Cloud computing and distributed systems.
Spectral efficient network and resource selection model in 5G networks
Building Integrated photovoltaic BIPV_UPV.pdf

06 HTML5 Mobile

  • 1. HTML5 Mobile APIs Use Mobile Device Capabilities From The Browser Tuesday, September 18, 12
  • 2. Web Tech History 1991 HTML 1994 HTML2 1996 CSS1 + JavaScript 1997 HTML4 1998 CSS2 2000 XHTML1 2002 Tableless Web Design 2005 Ajax 2009 HTML5 Tuesday, September 18, 12
  • 3. HTML5 What Syntactical Features (audio, video) Semantical Features (section, article) New APIs Tuesday, September 18, 12
  • 4. HTML5 How Progressive Enhancements Existing web sites can move to HTML5 Old browsers will still be able to use the page Modernizr: http://www.modernizr.com/ Tuesday, September 18, 12
  • 5. HTML5 New APIs Web Storage Geolocation Web SQL Device Orientation Application Cache Form Enhancements Web Workers Audio, Video Web Socket Canvas Desktop Notifications Web GL Drag & Drop History API File System API And More... Tuesday, September 18, 12
  • 6. HTML5 Mobile Related APIs Storage Geo Location Video Canvas Tuesday, September 18, 12
  • 7. Offline Storage Work Offline Store Persistent State Tuesday, September 18, 12
  • 8. Local Data Storage How do you store data on a client’s machine ? Tuesday, September 18, 12
  • 10. Local Storage Before HTML5: cookies were used to store data on the client side Cookies Disadvantages: Limited size (4k) Sent with every request Complex to use Tuesday, September 18, 12
  • 11. Local Storage A JavaScript API for storing client side data Can store up to 5MB (per site) Simple API Never run out of space Tuesday, September 18, 12
  • 12. Local Storage Store Data window.localStorage.setItem(“key”, “value”); Read Data window.localStorage.getItem(“key”); Remove Data window.localStorage.removeItem(“key”); Tuesday, September 18, 12
  • 13. Check Status Can check if online using: navigator.onLine Relevant events: online, offline Listen with: document.addEventListener(‘online’, ... ); Tuesday, September 18, 12
  • 14. Local Storage Can also use direct access on the storage object, so this code also works: window.localStorage.username = “Jimmy”; var username = window.localStorage.username; console.log(‘Hello ‘ + username); Tuesday, September 18, 12
  • 15. Local Storage Use clear() to delete all objects in the cache related to this page Use key() to get an item by its index (for example, to iterate all keys) Tuesday, September 18, 12
  • 16. Session Storage Interface is the same as localStorage Lifetime is only for the current browser window or tab (or browser session) Best used for temporary preferences that should not be shared between tabs Tuesday, September 18, 12
  • 17. Storage Example We’ll implement an address book app Keeps a list of contacts info: name, phone number, email Provide add/view/delete contacts Tuesday, September 18, 12
  • 18. Address Book examples/html5/contacts Tuesday, September 18, 12
  • 19. Exercise (1/2) Implement a todo list mini-app Use a single form to add tasks Use local storage to store them Display a list of active tasks Tuesday, September 18, 12
  • 20. Exercise (2/2) Use jQM to get a native look App should display a list of all active tasks Header button called “Add” should open a popup with new task description, and buttons to “Save” or “Abort” Bonus: Swipe to delete Tuesday, September 18, 12
  • 21. Offline Web App Online-Offline Apps Sync with the Cloud, but can suffer a downtime (Think Google Gears) Can run completely offline app as a standalone Mobile - Save bandwidth Tuesday, September 18, 12
  • 22. Offline Web App GET MANIFEST CACHE MANIFEST index.html style/main.css script/main.js Tuesday, September 18, 12
  • 23. Cache Manifest File Lists all the files that should be stored for offline access Enable with: <html manifest="example.appcache"> Tuesday, September 18, 12
  • 24. example.appcache CACHE MANIFEST Required header index.html CACHE MANIFEST stylesheet.css A list of cached files images/logo.png scripts/main.js Tuesday, September 18, 12
  • 25. Demo Caching A Website Tuesday, September 18, 12
  • 26. Offline Web App The cache manifest is divided to sections, the default is called CACHE Every file listed in the default CACHE section will be cached by the browser forever (or until explicitly deleted by the user) Tuesday, September 18, 12
  • 27. Offline Web App The NETWORK section lists files that should never be cached Best used for dynamic content (think gmail) Tuesday, September 18, 12
  • 28. Offline Web App The FALLBACK section lists fallback content that should be used if network is not available So, if you’re trying to read a message while offline, you can get a nice formatted error page Tuesday, September 18, 12
  • 29. Manifest Cache Cache the file locally, CACHE never refresh Files should not be NETWORK cached Cache a fallback FALLBACK content Tuesday, September 18, 12
  • 30. Offline App Exercise A Dynamic reader with two pages First lists available articles, the second displays a given article Use your favorite server side technology and jQM Which files do you put in each manifest section ? Tuesday, September 18, 12
  • 31. Manifest - The Good Can store any file locally Provides offline/online app functionality Transparent to the user Tuesday, September 18, 12
  • 32. Manifest - The Bad Not suitable for data storage Complex update logic Tuesday, September 18, 12
  • 33. Web SQL The final storage option for offline apps is the Web SQL Allows using a local database to better store relational data Best suited for hierarchical lists apps Tuesday, September 18, 12
  • 34. Q&A Storage Geo Location Video Canvas Tuesday, September 18, 12
  • 35. Geo Location Detect where your user is now Show nearby places Display location aware data Tuesday, September 18, 12
  • 36. Technologies GPS A-GPS Cell Information WiFi Positioning Tuesday, September 18, 12
  • 37. GPS Global Positioning System Accuracy error: 2-10m Requires clear sky view Time to position: 5 seconds - 5 minutes Tuesday, September 18, 12
  • 38. A-GPS Uses both GPS chip and network information to get location Much faster to get location Tuesday, September 18, 12
  • 39. Cell Information Uses cell towers to calculate a device’s location Accuracy: A block or up to some km Time to location: immediate Tuesday, September 18, 12
  • 40. WiFi Positioning Detect location using a list of wireless routers in your area Relies on existing router databases Tuesday, September 18, 12
  • 41. Location API Supported Platforms: iPhone 3.0+ Android 2.0+ Tuesday, September 18, 12
  • 42. Location API function get_location() {   navigator.geolocation.getCurrentPosition(show_map); } function show_map(position) {   var lat = position.coords.latitude;   var long = position.coords.longitude;   var when = position.timestamp;   // show me the map } Tuesday, September 18, 12
  • 43. Location API navigator.geolocation is the entry point for all location related calls Location querying is async, so a callback is supplied User will be asked permission to share location Tuesday, September 18, 12
  • 44. Location API iPhone browser asks user permissions before sharing location Tuesday, September 18, 12
  • 45. Location API Location API uses callbacks to perform error handling When working with location, always consider errors Tuesday, September 18, 12
  • 46. Location API getCurrentPosition( successCallback, optional errorCallback, optional config ); Tuesday, September 18, 12
  • 47. The Coord object coords.latitude coords.longitude coords.altitude coords.accuracy coords.altitudeAccuracy coords.heading coords.speed timestamp Tuesday, September 18, 12
  • 48. The Coord Object Not all fields will be available at all times Sizes are specified in meters and degrees timestamp is a DOMTimestamp (acts like a Date object) Tuesday, September 18, 12
  • 49. Location Config last parameter to getCurrentPosition is a config object there are 3 configuration options available: timeout maximumAge enableHighAccuracy Tuesday, September 18, 12
  • 50. Using Config window.navigator.geolocation.getCurrentPosition( successCallback, failureCallback, How long to wait before giving up { timeout : 0, (in ms) maximumAge : 60000, Try to use a cached value aged (in ms) enableHighAccuracy : false }); Use the most accurate positioning method Tuesday, September 18, 12
  • 51. Handle Errors The errorCallback takes a single argument called error object The object has two fields: error.code & error.message Use error.message for debug only Tuesday, September 18, 12
  • 52. Next: The Map Tuesday, September 18, 12
  • 53. Show The Map On the iPhone, a redirect to a google maps url starts the map application The Good: easy to use The Bad: user leaves the app Tuesday, September 18, 12
  • 54. Google Maps API A JS API to display embedded maps in web sites Works on both desktop and mobile devices Free to use Tuesday, September 18, 12
  • 55. Google Maps API Assign a special empty div that will contain the map. recommended size of the div is entire page. Display the map by creating a google.maps.Map object Place markers on the map using google.maps.Marker Full documentation: http://code.google.com/apis/maps/ documentation/javascript/ Tuesday, September 18, 12
  • 56. Demo Show Location On Map Tuesday, September 18, 12
  • 57. Location Tracking Receive notifications about location changes Can use for navigation apps, sport apps, and more Browser must remain open Tuesday, September 18, 12
  • 58. Location Tracking use watchPosition to start watching a user’s position The method returns a watch id. Keep it. When tracking is no longer needed, use clearWatch with the watch id to stop. The callback of watchPosition will get called every time location has changed Tuesday, September 18, 12
  • 59. Exercise: Where’s My Car Write a parking reminder app One button titled “parked” which marks current location and keeps it in local storage Another button titled “find” which shows a map leading to your car Keep data in local storage Tuesday, September 18, 12
  • 60. Q&A Storage Geo Location (iPhone, Android) Video (iPhone, Android) Canvas (iPhone, Android) Tuesday, September 18, 12
  • 61. VIDEO THE EASY WAY Tuesday, September 18, 12
  • 62. Video Tag HTML5 introduces a <video> tag to embed videos in a web page. Different browsers support different video formats. The <video> tag can specify multiple formats. Tuesday, September 18, 12
  • 63. Video Formats Video formats are like languages The same video can be encoded in different formats A browser must “speak the language” to be able to play the video Tuesday, September 18, 12
  • 64. Browser Support HTML5 spec does not define a video codec to use h.264 is the most widely supported. Plays on iPhone and Android Tuesday, September 18, 12
  • 65. The Markup Poster image file name <video poster=”star.png”> <source src=”zebra.mp4” /> Video file name. Usually mp4 </video> for mobile devices Tuesday, September 18, 12
  • 66. Limitations Video will start playing in a dedicated “player” window, when the user taps it It is not possible to auto play the video on mobile It is not possible to embed other content on the video on mobile Tuesday, September 18, 12
  • 67. Q&A Storage Geo Location Video Canvas (iPhone, Android) Tuesday, September 18, 12
  • 69. HTML5 Canvas A 2d graphics canvas for HTML apps Games Dynamic images Client-side painting (saves bandwidth) Tuesday, September 18, 12
  • 70. Hello Canvas An HTML element <canvas> on the markup JS code to do actual painting Tuesday, September 18, 12
  • 71. Hello Canvas The canvas element has no content and no border of its own A canvas keeps a painting context on which we perform the drawing First example uses context.fillText() examples/canvas/intro.html Tuesday, September 18, 12
  • 72. Basic Drawing Context object provides the drawing functions. Each takes coordinates and data. Drawing style is determined by setting attributes on the context object. Most style properties are plain text strings Tuesday, September 18, 12
  • 74. Drawing Rectangles Let’s start with drawing rectangles fillRect(x, y, w, h) note fillRect draws a strokeRect(x, y, w, h) filled rectangle, while clearRect(x, y, w, h) strokeRect draws just the outline fillStyle and strokeStyle determine the colors Tuesday, September 18, 12
  • 76. Drawing Paths A composite shape on the canvas is called “path” Paths are made of lines, arcs, curves and rectangles A path can be filled or stoked. Nothing is painted until either fill() or stroke() is called Tuesday, September 18, 12
  • 77. Drawing Paths moveTo(x, y) Lines are painted with lineTo and moveTo lineTo(x, y) stroke() performs the actual drawing Tuesday, September 18, 12
  • 78. Lines Example ctx.beginPath(); ctx.strokeStyle = "hsl(249, 41%, 50%)"; ctx.lineWidth = 6; ctx.moveTo(0, 0); ctx.lineTo(20, 10); ctx.lineTo(0, 20); ctx.stroke(); Cool Color Selector: http://mothereffinghsl.com/ Tuesday, September 18, 12
  • 79. Using The Image It’s possible to use an image drawn in a canvas for other elements get the image url using: canvas.toDataURL() use image url as a source attribute of an img tag Extra: draw on a hidden canvas Tuesday, September 18, 12
  • 80. Drawing Circles use arc() and arcTo() to arc(x, y, radius, draw circles or parts of startAngle, them endAngle, antiClockWise) Degrees are specified in radians. arcTo(x1, y1, Math.PI = 180 deg x2, y2, radius) remember to fill() or stroke() Tuesday, September 18, 12
  • 81. Exercise 1 Draw the image on the right Use moveTo and arc Bonus: add colors Tuesday, September 18, 12
  • 82. Exercise 2 Draw the image on the right Place pins randomly across the screen Tuesday, September 18, 12
  • 83. Advanced Canvas Transformations Image Filters Tuesday, September 18, 12
  • 84. Transformations supported translate(x, y) transformations: translation, scaling, rotate(angle) rotation scale(x, y) Transformations affect all drawing code performed after them Tuesday, September 18, 12
  • 85. Translation Move the origin of the canvas to another point on the canvas The new point is now (0, 0) This can make drawing code simpler Tuesday, September 18, 12
  • 86. Translation Example Use translation to paint the four painted rectangles on the right examples/html5/canvas/translate.html Tuesday, September 18, 12
  • 87. Scaling scales the rendering context size x and y are scale factors translate before scale to maintain position Tuesday, September 18, 12
  • 88. Scale Example examples/html5/canvas/scale.html Tuesday, September 18, 12
  • 89. Rotation Rotates a shape around its (0, 0) point of origin Angle is specified in radians. Math.PI = 180 deg (half a circle) Math.PI / 4 = 45 deg Translate before rotate to maintain position Tuesday, September 18, 12
  • 90. Example: Rotation ctx.translate(75,75); for (var i=1;i<6;i++){ ctx.save(); ctx.fillStyle = 'rgb('+(51*i)+','+(255-51*i)+',255)'; for (var j=0;j<i*6;j++){ // draw individual dots ctx.rotate(Math.PI*2/(i*6)); ctx.beginPath(); ctx.arc(0,i*12.5,5,0,Math.PI*2,true); ctx.fill(); } ctx.restore(); } Tuesday, September 18, 12
  • 91. Example: Rotation The background was painted with a gradient ctx.save(); fill var grad = ctx.createLinearGradient(0, 0, 150, 0); grad.addColorStop(0, "#888"); grad.addColorStop(1, "#eee"); Notice the save() and ctx.fillStyle = grad; restore() at the ctx.fillRect(0, 0, 150, 150); ctx.fill(); beginning and end. ctx.restore(); Now we can put the code inside a function, and it won’t affect outside code Tuesday, September 18, 12
  • 92. Exercise Draw the clock on the right Use rotate to simplify calculations Bonus: Show the time Tuesday, September 18, 12
  • 94. Drawing Images on Canvas It’s possible to paint a png or jpeg image on a canvas using drawImage Canvas also lets JS code take the pixels from the image into an array. Using this array, we can transform the pixels and write the result to a new canvas The operation is called filtering Tuesday, September 18, 12
  • 95. Image Drawing API drawImage(image, x, y) paint an entire image object on the canvas at position (x,y) drawImage(image, x, y, w, h) paint an entire image object on the canvas, scaling it to size (w,h) drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) paint a slice of the image on a canvas, can use dw,dh to scale Tuesday, September 18, 12
  • 96. Image Filters For the next few slides, we’ll create a Filters object. Each filter is a function of that Filters object The Filters object is responsible for reading pixel data and interacting with the canvas A filter function takes pixel data and manipulates it Tuesday, September 18, 12
  • 97. Filters Code When testing on desktop, some canvas.toDataURL() browsers will throw ctx.getImageData(sx, sy, sw, sh) security exceptions if ctx.putImageData(data, dx, dy) the page is read locally. Code: examples/html5/canvas/filters.html Tuesday, September 18, 12
  • 98. Canvas Exercise Implement a mobile drawing app using the canvas and touch events App should have a footer with a selection of colors. Tapping a color sets current color Tapping anywhere on screen should draw in the selected color Bonus: share photo on server Tuesday, September 18, 12
  • 100. Thank You Ynon Perek ynonperek@yahoo.com ynonperek.com Tuesday, September 18, 12