DMW PPT13
DMW PPT13
nl
O
Session: 13
se
Canvas and Web
U
Storage in HTML5
tre
en
C
h
ec
pt
rA
Fo
Objectives
y
nl
O
se
Describe Canvas in HTML5
Explain the procedure to draw lines
U
Explain the procedure to use color and transparency
Explain the procedure to work with various drawing objects
tre
Describe working with images and text
Describe the procedure to create Web page events with JavaScript and jQuery
en
Describe the process of including external content in Web pages
Explain Web storage in HTML5
C
Explain session storage
Explain local storage
h
Explain the Indexed DB API
Describe a native app
ec
pt
Explain the difference between native apps and HTML5 apps
Describe the advantages of native and HTML5 apps
rA
y
The <canvas> element in HTML5 can be used to draw shapes on Websites as well
nl
as to dynamically draw graphics using JavaScript.
O
se
The <canvas> element is represented like a rectangle on a page and allows the
user to draw arcs, text, shapes, gradients, and patterns.
U
tre
The <canvas> in HTML5 is like <div>, <table>, or <a> tag except that the content
used in it is rendered through JavaScript.
en
C
The <canvas> element does not contain any drawing abilities, instead, drawing is
done using a JavaScript code.
h
ec
To make use of <canvas> element, a user has to add <canvas> tag on the HTML
pt
page.
rA
y
The Code Snippet demonstrates the use of <canvas> element.
nl
<!DOCTYPE HTML>
O
<html>
<head>
se
<title> Canvas </title>
<style>
U
canvas{border: medium double red; margin: 4px}
</style>
tre
</head>
<body>
<canvas width="278" height="200"></canvas>
en
</body>
</html>
C
In the code, <style> element is used to display border of <canvas> element.
The height and width attributes specify size of <canvas> element on the page.
h
ec
To draw a <canvas> element, the user can use a context object.
pt
rA
The context object contains the drawing functions for a specific style of graphics.
Fo
y
The <canvas> element in DOM exposes the HTMLCanvasElement interface.
nl
O
This interface provides the methods and properties for changing the presentation and layout of canvas
elements.
se
The HTMLCanvasElement has a getContext(context) method that returns the drawing context for the
canvas.
U
The Code Snippet demonstrates the 2d context object for the canvas.
tre
<!DOCTYPE HTML>
<html>
en
<head>
<title> Canvas </title>
C
<script>
window.onload = function()
{
h
var canvas = document.getElementById('mCanvas');
ec
var ctext = canvas.getContext('2d');
ctext.beginPath();
ctext.rect(18, 50, 200, 100);
pt
ctext.fillStyle = "DarkBlue";
ctext.fill();
rA
};
</script>
</head>
Fo
<body>
<canvas id="mCanvas" width="578" height="200"></canvas>
</body>
</html>
Designing Modernistic Websites © Aptech Limited 5
5
Drawing a Line in Canvas 1-3
You can create lines in a canvas using the stroke(), beginPath(), lineTo(),
y
nl
and moveTo() methods.
Following is the syntax to create a line in canvas:
O
se
Syntax:
ctext.beginPath();
U
ctext.moveTo(x,y);
tre
ctext.lineTo(x,y);
ctext.stroke();
en
C
where,
h
ctext - specifies a context object
ec
beginPath() - Specifies a new drawing path
moveTo() - Specifies the creation of new sub path to the given position
pt
lineTo() - Specifies the drawing of a line from the context position to the given position
rA
y
nl
<!DOCTYPE HTML>
<html>
O
<head>
<title>Line</title>
<style>
se
body
{
margin: 0px;
U
padding: 0px;
}
tre
#mCanvas
{
border: 1px solid red;
en
}
</style>
<script>
C
window.onload = function() {
var canvas = document.getElementById("mCanvas");
var ctext = canvas.getContext("2d");
h
ctext.beginPath();
ec
ctext.moveTo(100, 150);
ctext.lineTo(250, 50);
ctext.lineWidth = 5;
pt
ctext.strokeStyle = "blue";
ctext.stroke();
rA
};
</script>
</head>
Fo
<body>
<canvas id="mCanvas" width="360" height="200"></canvas>
</body>
</html>
Designing Modernistic Websites © Aptech Limited 7
7
Drawing a Line in Canvas 3-3
y
nl
In the code, the height and width attributes are defined.
O
The initializer function has the DOM object which is accessed through the id attribute
se
and gets a 2d context by using the getContext() method.
U
The beginPath() method is called through the context object to draw the path of the
line.
tre
The moveTo(100,150) method is called that creates a new path for the given point
en
to place the drawing cursor and moves the position of the window to the upper-left
corner by giving the x and y coordinates.
C
The lineTo(250,50) method is called to draw the line from the context point to
h
given point.
ec
pt
The lineWidth property is specified as 5 to define the width of the line on the
canvas.
rA
y
HTML5 canvas allows the user to work with different types of drawing objects.
nl
Following objects can be drawn on a canvas element:
O
➢ Rectangle
se
With HTML5 canvas, the user can create a rectangle using the rect() method.
U
The HTML5 canvas is placed by using the x and y parameters and appropriately sized through
height and width properties.
tre
Following table lists the common properties and methods of various shapes:
en
Properties and Methods Description
The values for this property can be gradient, pattern, or a CSS color.
C
fillStyle The default property style is solid black, but user can set color
according to the requirements.
h
fillRect(x, y, width, Enables the user to draw a rectangle with the existing fill style.
height)
ec
pt
strokeStyle The values for this property can be gradient, pattern, or a CSS color.
rA
strokeRect(x, y, width, Enables the user to draw a rectangle with the existing stroke style. This
height) property is used to draw the edges of the rectangle.
Fo
y
nl
<!DOCTYPE HTML>
<html>
O
<head>
<style>
se
#mCanvas {
border: 1px solid green;
}
U
body {
margin: 0px;
tre
padding: 0px;
}
</style>
en
<script>
window.onload = function() {
C
var canvas = document.getElementById('mCanvas');
var ctext = canvas.getContext('2d');
ctext.beginPath();
h
ctext.rect(30, 50, 150, 100);
ec
ctext.fillStyle = "Magenta";
ctext.fill();
ctext.lineWidth = 5;
pt
ctext.strokeStyle = 'black';
ctext.stroke();
rA
};
</script>
</head>
Fo
<body>
<canvas id="mCanvas" width="278" height="200"></canvas>
</body>
</html>
Designing Modernistic Websites © Aptech Limited 10
10
Working with Drawing Objects 3-11
In the code, the height and width attributes are defined.
y
nl
The initializer function has the DOM object which is accessed through
O
the id attribute and gets a 2d context by using the getContext()
method.
se
The beginPath() method is called through the context object to draw Output:
U
the rectangle.
tre
The rect(30, 50, 150,100) method takes x, y, height, and width as
en
the parameters.
C
The fillStyle property fills the rectangle with magenta color.
h
The fill() method is used to paint the rectangle.
ec
The lineWidth property is specified as 5 to define the width of line
pt
on the canvas.
rA
black.
y
➢ Arcs
nl
O
With HTML5 canvas, the user can create an arc by using the arc() method.
se
Arcs are represented using a start angle, an end angle, a radius, a center
point, and the drawing direction (anticlockwise or clockwise).
U
tre
The syntax to draw an arc in HTML5 is as follows:
en
Syntax:
C
arc(x, y, radius, startAngle, endAngle, anticlockwise)
h
ec
where,
x, y - Specifies the coordinates of the center of an arc
pt
radius - Specifies the distance from the center to any point on the circle
startAngle, endAngle - Specifies the start and end points in the arc
rA
anticlockwise - Draws the arc clockwise or anticlockwise and accepts a boolean value
Fo
y
nl
<!DOCTYPE HTML>
<html>
O
<head>
<style>
body
se
{
margin: 0px;
padding: 0px;
U
}
#mCanvas {
tre
border: 1px solid black; }
</style>
<script>
en
window.onload = function() {
var canvas = document.getElementById("mCanvas");
var ctext = canvas.getContext("2d");
C
var x = canvas.width / 2;
var radius = 75;
var startAngle = 1.1 * Math.PI;
h
var endAngle = 1.9 * Math.PI;
ec
var ctrClockwise = false;
ctext.beginPath();
ctext.arc(x, y, radius, startAngle, endAngle, ctrClockwise);
pt
ctext.lineWidth = 25;
// line color
rA
ctext.strokeStyle = "DarkGreen";
ctext.stroke();
};
Fo
</script> </head>
<body>
<canvas id="mCanvas" width="278" height="250"></canvas>
</body></html>
y
In the code, the beginPath() method is called through the context object to
nl
draw an arc by using the arc() method which has x, y, and radius as the
O
parameters.
The startAngle and the endAngle are the start and end points of the arc.
se
The anticlockwise specifies the direction of the arc between the two start
and end points.
U
Following figure displays an arc in HTML5 canvas.
tre
en
C
h
ec
pt
rA
Fo
y
➢ Circle
nl
O
In HTML5, you can draw a circle using the arc() method.
You have to set the start angle with 0 and the end angle is specified as 2 *
se
PI.
Following is the syntax to draw a circle in HTML5 is as follows:
U
Syntax:
tre
arc(x, y, radius, startAngle, endAngle, anticlockwise)
en
C
where,
x, y - Specifies the coordinates of the center of an arc
h
radius - Specifies the distance from the center to any point on the circle
ec
startAngle, endAngle - Specifies the start and end points in the arc
pt
anticlockwise - Draws the arc clockwise or anticlockwise and accepts a
boolean value
rA
Fo
y
<html>
nl
<head>
<style>
O
body {
margin: 0px;
padding: 0px;
se
}
#mCanvas
U
{
border: 1px solid blue;
}
tre
The Code Snippet </style>
<script>
demonstrates how to window.onload = function() {
en
var canvas = document.getElementById("mCanvas");
create a circle using var ctext = canvas.getContext("2d");
HTML5. var ctrX = canvas.width / 2;
C
var ctrY = canvas.height / 2;
var radius = 70;
h
ctext.beginPath();
ctext.arc(ctrX, ctrY, radius, 0, 2 * Math.PI, false);
ec
ctext.fillStyle = "DarkOrchid";
ctext.fill();
ctext.lineWidth = 4;
pt
ctext.strokeStyle = "black";
ctext.stroke();
rA
};
</script>
</head>
Fo
<body>
<canvas id="mCanvas" width="356" height="150"></canvas>
</body>
</html>
Designing Modernistic Websites © Aptech Limited 16
16
Working with Drawing Objects 9-11
y
In this code, a circle is defined by using the arc() method which has ctrX, ctrY, and
nl
radius as the parameters.
O
To define the arc with the points the startAngle is set to 0 and the endAngle is
specified as 2*PI.
se
The anticlockwise defines the direction of the path of an arc between the two start
and end points.
U
tre
➢ Bezier Curves
en
Using HTML5 canvas, you can create a Bezier curve using the bezierCurveTo()
C
method.
Bezier curves are represented with the two control points, context points, and an
h
end point.
ec
pt
rA
Fo
y
<!DOCTYPE HTML>
nl
<html>
<head>
O
<style>
body
{
se
margin: 0px;
padding: 0px;
U
#mCanvas
demonstrates how to {
tre
border: 1px solid maroon;
create a Bezier curve }
using HTML5. </style>
en
<script>
window.onload = function()
{
C
var canvas = document.getElementById("mCanvas");
var ctext = canvas.getContext("2d");
ctext.beginPath();
h
ctext.moveTo(188, 130);
ec
ctext.bezierCurveTo(140, 10, 388, 10, 288, 100);
ctext.lineWidth = 15;
// line color
pt
ctext.strokeStyle = "purple";
ctext.stroke();
rA
};
</script>
</head>
Fo
<body>
<canvas id="mCanvas" width="378" height="200"></canvas>
</body>
</html>
Designing Modernistic Websites © Aptech Limited 18
18
Working with Drawing Objects 11-11
➢ Quadratic Curves
y
nl
HTML5 canvas allows the user to create quadratic curves using the quadraticCurveTo() method.
O
Quadratic curves are represented through the context point, an end point, and a control point.
se
<!DOCTYPE HTML>
<html>
<head>
U
<style>
body
{
tre
margin: 0px;
The Code Snippet padding: 0px;
demonstrates how to }
en
#mCanvas {
create a quadratic curve border: 1px solid #9C9898;
}
using HTML5.
C
window.onload = function() {
var canvas = document.getElementById("mCanvas");
var ctext = canvas.getContext("2d");
h
ctext.beginPath();
ec
ctext.moveTo(178, 150);
ctext.quadraticCurveTo(220, 0, 320, 150);
ctext.lineWidth = 15;
pt
// line color
ctext.strokeStyle = "Fuchsia";
rA
ctext.stroke();
};
</script>
</head>
Fo
<body>
<canvas id="mCanvas" width="378" height="200"></canvas>
</body>
</html>
Designing Modernistic Websites © Aptech Limited 19
19
Working with Images
In HTML5, the user can draw image objects on canvas using the drawImage() method.
y
The drawImage() method can also draw parts of an image and increase or reduce the size of the image.
nl
The image object can be a video, an image, or another canvas element.
O
<!DOCTYPE HTML>
<html>
se
<head>
<style>
body {
U
margin: 0px;
padding: 0px;
tre
}
#mCanvas {
border: 1px solid #9C9898;
en
}
The Code Snippet </style>
<script>
C
demonstrates how window.onload = function() {
var canvas = document.getElementById("mCanvas");
to create an image var ctext = canvas.getContext("2d");
h
using HTML5. var imgObj = new Image();
ec
imgObj.onload = function()
{
ctext.drawImage(imgObj, 69, 50);
pt
};
imgObj.src = "bird.jpg";
rA
};
</script>
</head>
Fo
<body>
<canvas id="mCanvas" width="368" height="300"></canvas>
</body>
</html>
Designing Modernistic Websites © Aptech Limited 20
20
Working with Text 1-2
y
HTML5 canvas enables you to set the font, style, and size of text by using the font properties.
nl
The font style can be italic, normal, or bold.
O
To set the text color, the fillStyle property of the canvas can be used.
The Code Snippet demonstrates how to set the font, size, style, and color of the text on a HTML5 canvas.
se
<!DOCTYPE HTML>
<html>
U
<head>
<style>
tre
body {
margin: 0px;
padding: 0px;
en
}
#mCanvas {
border: 1px solid blue;
C
}
</style>
<script>
h
window.onload = function() {
ec
var canvas = document.getElementById("mCanvas");
var ctext = canvas.getContext("2d");
ctext.font = "italic 30pt Calibri";
pt
ctext.fillStyle = "MediumVioletRed";
ctext.fillText("Welcome to HTML5!", 40, 100);
rA
};
</script>
</head>
Fo
<body>
<canvas id="mCanvas" width="380" height="170"></canvas>
</body>
</html>
y
The Code Snippet demonstrates the use of stroke text in HTML5 canvas.
nl
<!DOCTYPE HTML>
O
<html>
<head>
se
<style>
body {
margin: 0px;
U
padding: 0px;
}
#mCanvas {
tre
border: 1px solid black;
}
</style>
en
<script>
window.onload = function() {
C
var canvas = document.getElementById("mCanvas");
var ctext = canvas.getContext("2d");
var x = 80;
h
var y = 110;
ec
ctext.font = "40pt Calibri";
ctext.lineWidth = 2;
// stroke color
pt
ctext.strokeStyle = "Brown";
ctext.strokeText("HTML5", x, y);
rA
};
</script>
</head>
<body>
Fo
y
<!DOCTYPE HTML>
nl
<html>
<head>
O
<style>
body {
se
margin: 0px;
padding: 0px;
}
U
#mCanvas {
border: 1px solid black;
tre
</style>
demonstrates the use <script>
window.onload = function() {
en
of globalAlpha var canvas = document.getElementById("mCanvas");
var ctext = canvas.getContext("2d");
property. ctext.fillStyle = "Indigo";
C
ctext.strokeStyle ="black";
ctext.lineWidth=2;
h
ctext.font = "italic 30pt Calibri";
ctext.fillText("HTML5", 40, 100);
ec
ctext.strokeText("HTML5", 40, 100);
ctext.fillStyle="blue";
pt
ctext.globalAlpha=0.5;
ctext.fillRect(100, 10, 150, 100);
rA
};
</script>
</head>
<body>
Fo
y
jQuery also offers different events to deal with common interactions when the user
nl
moves the mouse or switches between two actions while clicking.
O
Following are the events:
➢ hover() event
se
The mouseenter and mouseleave are the two events often used together.
U
jQuery provides a hover() function that accepts two parameters.
tre
The first parameter executes when the mouse moves over the element and the second function
executes when the mouse moves away from the element.
en
<!DOCTYPE html>
<html>
C
<head>
<script src="jquery-1.7.2.min.js"></script>
<script>
h
$(document).ready(function(){
The Code Snippet
ec
$("p").hover(function(){
$("p").css("background-color","red");
demonstrates the },function(){
pt
$("p").css("background-color","maroon");
hover event. });
rA
});
</script>
</head>
Fo
<body>
<p>Hover the mouse on this line.</p>
</body>
</html>
y
➢ toggle() event
nl
The toggle() event works in a similar manner as that of the hover() event, except that
O
it responds to mouse clicks.
se
The toggle() function accepts more than two functions as arguments.
All the functions passed to the toggle() event will react to its corresponding click action.
U
The Code Snippet demonstrates the toggle event.
tre
<!DOCTYPE html>
<html>
en
<head>
<script src="jquery-1.7.2.min.js"></script>
<script>
C
$(document).ready(function(){
$("p").toggle(function(){
h
$("body").css("background-color","blue");},
function(){
ec
$("body").css("background-color","pink");},
function(){
pt
$("body").css("background-color","grey");}
);
rA
});
</script>
</head>
Fo
<body>
<p>Click to change the colors.</p>
</body>
</html>
Designing Modernistic Websites © Aptech Limited 25
25
Using Events with jQuery 3-3
y
Following figure displays Following figure displays the
nl
the toggle effect to blue: toggle effect to pink:
O
se
U
tre
en
C
Following figure displays the toggle effect to grey:
h
ec
pt
rA
Fo
y
HTML5 introduces the <eventsource> tag that allows the user to push
nl
external content in the Web page. This model is referred to as push model.
O
se
Since the <eventsource> tag is not supported in many browsers, users make
use of the <embed> tag for this purpose.
U
The <embed> tag is a new element in HTML5 and it is represented as a
tre
container for an interactive content or an external application.
en
The <embed> tag is often used to add elements such as image, audio, or video
C
on a Web page.
h
The Code Snippet demonstrates the use of <embed> tag.
ec
pt
<embed src="mymovie.mp3" />
rA
In this code, the src attribute specifies the path of an external file to embed.
Fo
y
Traditionally, over the last few decades, Web applications have been using cookies to store small
nl
amounts of information on a user's computer.
O
A cookie is a file that stores user-related information and may either be temporary or permanent.
se
A cookie can be created for login details which can be saved for a specified period on a user's
computer.
U
Drawbacks of cookies are as follows:
tre
o Cookies slow down the performance of Web application, as they are included with every HTTP request
o Cookies cannot be considered as safe means for transmission of sensitive data
en
o Cookies cannot store large amount of information, as they have a limitation of size of four kb
W3C has designed a specification named Web Storage API which offer a solution to store data on the client-side
C
Is a W3C specification and certain browsers refer to it as 'DOM Storage'.
h
ec
Provides functionality for storage of data on the client-side that is on user's machine.
pt
Stores data that can cater for both temporary as well as permanent needs.
rA
Offers more control than traditional cookies, and is easy to work with.
Fo
Was originally a part of the HTML5 specification, but now it is present in a separate specification and stores a maximum of five mb of
information per domain.
Designing Modernistic Websites © Aptech Limited 28
28
Web Storage versus Cookies
y
Some key differences between cookies and Web storage are as
nl
follows:
O
se
Cookies are meant to be read on the server-side, whereas Web storage is
available only on the client-side.
U
tre
Cookies are sent along with each HTTP request to the server, whereas Web
storage data is not carried over to the server.
en
Cookies result in bandwidth overhead and thus lead to high costs, as they are
C
sent with each HTTP request. The Web storage is stored on the user's hard
drive, so it costs nothing to use.
h
ec
With cookies, the information data that could be stored is four kb, whereas
pt
with Web storage, a large amount of data can be stored upto five mb.
rA
Fo
y
nl
Web storage is browser-specific and the location where the Web storage data
is stored depends on the browser.
O
Each browser's storage is separate and independent, even if it is present on
se
the same machine.
U
HTML5 Web storage is implemented natively in most Web browsers, so one
can use it even when third-party browser plug-in is not available.
tre
Following table lists the support of various browsers for HTML5 Web storage:
en
C
Browser Version
h
IE
ec 8.0+
pt
Firefox 3.6+
rA
Safari 4.0+
Fo
Chrome 5.0+
Opera 10.5+
y
Two types of HTML5 Web storage are namely, session storage and local storage.
nl
O
Both session and local storage enable to store around five mb of data per domain.
To check for browser support of HTML5 Web storage, a property named localStorage or sessionStorage is
se
available as a global variable for the window object.
If there is no support, the localStorage or sessionStorage property will be undefined.
U
tre
<!DOCTYPE html>
<html>
<head>
en
<title>Support for Web Storage</title>
<script>
C
function checkSupport() {
Code Snippet if (('sessionStorage' in window) && window['sessionStorage']
demonstrates the !== null)
h
{
script to check the
ec
alert("Your browser supports Web Storage");
support for HTML5 return;
Web storage in the }
pt
alert("Your browser does not support Web Storage");
browser. }
rA
</script>
</head>
<body onload="checkSupport();">
Fo
</body>
</html>
y
Keeps track of data specific to one window or tab and discards it as soon the user closes the tab (or window) that
nl
he/she was working with.
O
Lasts for the entire duration of the session and hence, is not persistent.
se
Makes use of named key/value pairs which are enclosed within double quotes.
Stores the data using the named key, whereas the data is retrieved by referring to that key.
U
Key is a string, whereas the value stored in the key can be of any data type such as string, boolean, integer, or float.
tre
Regardless of the type of data that is stored, it is actually stored internally as a string.
Storing and retrieving data of other types requires the use of functions to convert them into the appropriate data
en
types.
Following table lists some examples of named key/value pairs belonging to various data types:
C
Key Value
h
ec
Name Sarah
book C Programming
pt
Email info@me.com
rA
age 28
uservalid true
y
Storing and retrieving data - setItem() and getItem() methods are used to
nl
store and retrieve data from session storage respectively.
O
Syntax to use setItem() and getItem() methods is as follows:
se
U
To assign data
sessionStorage.setItem(key, value);
tre
where,
key: Is the named key to refer to the data.
en
value: Is the data to be stored.
C
To retrieve data
var item = sessionStorage.getItem(key);
h
where,
ec
item: Is the variable into which the data will be saved.
key: Is the named key to refer to the data.
pt
To remove data
rA
sessionStorage.removeItem(key);
where,
key: Is the named key to refer to the data.
Fo
To clear data
sessionStorage.clear(); 33
33
Designing Modernistic Websites © Aptech Limited
Session Storage 3-3
y
nl
Code Snippet demonstrates how to set and retrieve a name using sessionStorage
O
object.
se
<!DOCTYPE html>
U
<html>
<head>
tre
<title>Working with Session Storage</title>
<script>
en
function testStorage() {
if (('sessionStorage' in window) &&
window['sessionStorage'] !== null)
C
{
sessionStorage.setItem('name', 'Sarah');
h
alert('The name is: ' +
sessionStorage.getItem('name'));
} ec
pt
}
</script>
rA
</head>
<body onload=" testStorage();">
Fo
</body>
</html>
y
nl
O
Enables to save data for longer periods on the user's computer, through the
se
browser.
U
tre
Data is persistent and can be retrieved when a user visits the site again.
en
Is used, if data needs to be stored for more than a single session.
C
h
Works in a similar fashion as session storage and uses similar functions,
ec
such as setItem(), getItem(), removeItem(), and clear().
pt
rA
Fo
y
<html>
nl
<title> Local Storage </title>
<script>
O
function store() {
if (('localStorage' in window) && window['localStorage'] !==
se
null) {
var username = document.getElementById('username').value;
Code Snippet localStorage.setItem('username', username);
U
demonstrates use } else {
alert ('your browser does not support storage');
of local storage to
tre
}
}
store the value of function cancel_store() {
en
username field if (('localStorage' in window) && window['localStorage'] !==
null) {
and later, retrieve localStorage.removeItem('username');
C
} else {
the value in alert ('your browser does not support storage');
h
another Web page. }
ec
}
</script>
</head>
pt
<body>
<form method="get" action="success.html">
rA
y
Code Snippet shows the success.html page that retrieves value from the local
nl
storage and displays it in the browser.
O
<!DOCTYPE html>
se
<head>
<title> Local Storage </title>
U
<script>
tre
function print() {
var username = localStorage.getItem('username');
en
document.getElementById('lblMsg').innerHTML = 'Username:
C
is <b>'+ username+'</b>';
}
h
</script>
</head>
ec
pt
<body onload="print()">
rA
<label id="lblMsg"></label><br>
</body>
Fo
</html>
y
nl
O
A database is an organized collection of data.
se
Databases, such as relational database stores the data in the form of tables.
U
tre
A table comprises rows and columns that are used to store data.
en
The representation of data from a table is in the form of records.
C
h
HTML5 has introduced a new Web Storage API which can host Web databases
locally within the user browser.
ec
pt
Web databases are not like relational databases in terms of functionality.
rA
Fo
y
nl
Indexed Database API is a specification also known as IndexedDB.
O
se
It is basically an object store that can be used to store and manipulate data on
the client-side.
U
The object store is the primary storage mechanism that stores the object in
tre
the database managed locally within the browser.
en
It enables to create an object store of a particular type in which objects can be
persisted using JavaScript.
C
IndexedDB enables to create Web applications with rich query abilities and
h
which can work both online and offline.
ec
pt
IndexedDB supports two types of API namely, synchronous and asynchronous.
rA
The synchronous API can be used with WebWorkers, whereas asynchronous API
Fo
y
nl
IndexedDB API is implemented using window.indexedDB object.
O
se
Browsers implement the IndexedDB object with their own prefixes. For example, Chrome
browser uses the webkit prefix, whereas Mozilla supports –moz prefix.
U
tre
Following table lists the browser support for the IndexedDB API:
en
IE Firefox Chrome Safari Opera iOS Safari
C
6.0 - - - - 3.2
h
ec
7.0 8.0moz - pt - - 4.0-4.1
- 12.0moz 19.0webkit - - -
y
Some of the basic constructs of IndexedDB API are as follows:
nl
The IndexedDB database comprises more than one object store. Each
O
Database database contains a name that identifies the origin of the database and a
version number which identifies the lifetime of the database.
se
Object Store Is the main mechanism to store data in a database. They hold the data
U
stored in the database in the form of records.
tre
Keys Each record stored in the database is identified by a unique key.
en
Values Are the data stored in the records.
C
h
Key Path Is a string that defines how the browser should extract key from a value.
ec
The key from a value can be extracted either in the object store or index.
pt
Index Is used when the data from the object store is retrieved based on some
other values other than a key.
rA
y
Some of the basic constructs of IndexedDB API are as follows:
nl
O
se
U
Requests - Operations, such as reading or writing on the database is
performed using a request. Each request contain attributes, such as flag,
tre
source object, result, and error.
en
Cursor - Is a mechanism used to retrieve multiple records from a database.
C
h
Key Range - Records from the object stores and indexes are retrieved using
ec
keys or key ranges. A key range refers to retrieval of data between specified
bounds based on the keys.
pt
rA
Fo
y
Steps to implement the IndexedDB API in a Web application are as
nl
follows:
O
se
Work with the
U
retrieved
Perform some results
tre
database
Start a operations,
en
transaction such as add
Create an and retrieve
C
object store
Open a
h
database
ec
pt
rA
Fo
y
Opening a Database
nl
O
Code Snippet shows the code to open a database
se
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB ||
window.msIndexedDB;
var request = indexedDB.open("CompanyDB", 1);
U
request.onsuccess = function (event) {
. . .
tre
};
request.onerror = function (event) {
console.log("IndexedDB error: " + event.target.errorCode);
en
};
Updating Version of a Database
C
After the database is opened, it can be structured by providing a version number which helps to set up the
h
database.
ec
pt
Code Snippet shows the code that specifies the version number to the database
rA
setVrequest.onsuccess = function(event) {
. . .
}
y
Creating the Object Store
nl
O
Structure of IndexedDB database facilitates the storage of multiple object
stores.
se
U
Object store is created using createObjectStore() method which accepts two
arguments namely, the store name and a parameter object.
tre
Code snippet demonstrates the code to create an object store named
en
employee in the CompanyDB database.
var employeeData = [
C
{ name: "John Smith", email: "john@company.com" },
{ name: "Jill Patrick", email: "jill@company.com" },
h
{ name: "Rock Ethan", email: "rock@company.com" },
ec
{ name: "Daniel Andrew", email: "daniel@company.com" }
pt
];
var objectStore = db.createObjectStore("employee", {
rA
objectStore.put(employeeData[i]);
alert("Record added");
}
Designing Modernistic Websites © Aptech Limited 45
45
Implementing IndexedDB API 4-5
y
Creating a Transaction
nl
O
To perform database operation, such as retrieving data from the object store, IndexedDB
provides a IDBTransaction object.
se
U
This object can be created in three mode namely, read-only, read-write, and snapshot.
tre
en
Code Snippet demonstrates the code to retrieve data from the employee
object store using get() function of the transaction object.
C
var trans = db.transaction(["employee"],
h
IDBTransaction.READ_WRITE).objectStore("employee");
var request = trans.get(2);
request.onerror = function(event) {
// Handle errors! ec
pt
};
rA
request.onsuccess = function(event) {
// Do something with the request.result!
alert("Name: " + request.result.name);
Fo
};
y
Opening a Cursor
nl
O
Cursor is used to retrieve multiple records from an object store.
se
U
They can be used when the value of key path is not known. They are part of a
transaction and are opened for a particular object store.
tre
en
Code Snippet demonstrates the code to retrieve multiple records from the
C
employee object store.
h
ec
store = db.transaction("employee").objectStore("employee");
store.openCursor().onsuccess = function(event) {
pt
var cursor = event.target.result;
if (cursor) {
rA
}
};
Designing Modernistic Websites © Aptech Limited 47
47
Limitations of IndexedDB API
y
Design limitations for IndexedDB API used for client-side storage of
nl
data are as follows:
O
se
Internationalized sorting deals with sorting of string data. As the database
U
does not follow any international order for storing data, internationalized
tre
sorting is not supported by the API.
en
IndexedDB API does not synchronize client-side database with the server-
side databases.
C
h
IndexedDB API supports querying the client-side database, but does not
ec
support the use of operators, such as LIKE that is used by Structured Query
Language (SQL).
pt
rA
Fo
y
nl
O
A native application also known as native app is an application program that
is built for using it on a particular device or platform.
se
U
tre
A native app, when compared with Web app is installed on a device and has a
faster response, because it has a direct user interface.
en
C
h
ec
pt
rA
Fo
y
nl
O
HTML5 Web apps are accessible and used on any devices through Web
browser similar to the mobile Website.
se
Web apps have the ability of offline access which means that the user need
U
not have a network connection.
tre
Following table lists differences between native apps and HTML5 apps:
en
C
Native Apps HTML5 Apps
h
ec
Native Apps runs on iOS and Android devices HTML5 Apps runs on a Web server, usually in a
that can be downloaded or purchased from the Web browser.
online app stores.
pt
rA
Native Apps use programming language, such Web developers use HTML, JavaScript, and
as Java for Android devices and Objective C for CSS. They need to acquire the skills of Java and
iOS devices. objective C for writing native applications.
Fo
y
Some of the reasons to develop HTML5 applications are as follows:
nl
O
Users cannot Cannot identify whether they are working on a hybrid HTML5-native application or a fully native application or an
identify the HTML5 application.
se
differences
U
Users adjust HTML5 apps can be viewed on any devices that contains Web browser.
styles for
tre
devices
en
Upcoming HTML5 does not support all features on a device, but it is coming up with new functionalities.
functionalities
C
h
Improving Many developers learn new methods to improve the performance of Web.
ec
Performance pt
If the developers want that their application to be used by a large number of users, then they should design and
Independent develop applications for both mobile users as well as desktop users.
rA
device
Developers are HTML5 developers are not restricted to an app store. Instead, they can create applications and sell them like any
Fo
y
Major advantage of native apps over HTML5 apps is that they are faster than
nl
HTML5 apps. Native apps provide more benefits over HTML5 apps. These are as
O
follows:
se
U
Providing access Push Accessing device Superior graphics
Uploading Offline access
tre
to device notifications files than HTML5
hardware Files
en
There are no APIs Native apps The push Native apps HTML5 has a canvas HTML5 provides
available for can access the notifications are communicate with element, but it will access to offline
C
accelerometers, file system in sent always files on devices, such not create a full 3D Web applications.
cameras, or any Android and with an open IP as contacts and experience. However, a native
h
other device some files in connection to photos. However, app is stored on
applications on
ec
hardware for iOS. However, these files cannot be local machine, so
HTML5 apps. the HTML5 the iOS device. seen from HTML5 that users do not
file API does app. require access to
pt
not work on the Web to work
with the
rA
Android or
iOS. application.
Fo
y
Users have a choice of developing their application in HTML5 and convert them
nl
into a native app
O
Users can use some tools to convert an HTML5 app to Native app and they are as
se
follows:
U
tre
en
PhoneGap Appcelerator
C
Is a cross-platform mobile
Is an HTML5 app that
application development
h
allows the user to create
support and allows the
native apps with Web
technologies and is
ec
accessible to app stores
users to create Android,
iOS, and mobile Web
pt
apps.
and APIs.
rA
Fo
y
and also add text for enhancing the user experience on Web pages.
nl
❖ To create a line, on a canvas one can use the stroke(), beginPath(), lineTo(), and moveTo() methods.
O
❖ Arcs are represented using a start angle, an end angle, a radius, a center point, and the drawing direction
se
(anticlockwise or clockwise).
❖ With HTML5 canvas, the user can create a rectangle using the rect() method.
U
❖ Bezier curves are represented with the two control points, context points, and an end point.
tre
❖ HTML5 canvas allows the user to create quadratic curves using the quadraticCurveTo() method.
en
❖ HTML5 canvas enables the user to draw image object on canvas using the drawImage() method.
❖ Web Storage is a W3C specification that provides functionality for storing data on the client-side for both
temporary as well as permanent needs.
C
❖ HTML5 Web applications make use of Web storage to implement client-side persistent storage and they
h
are: session storage and local storage.
❖
ec
Session storage keeps track of data specific to one window or tab.
pt
❖ The setItem() and getItem() methods are used to store and retrieve the data from session storage.
rA
❖ Local storage enables to save data for longer periods on the user's computer, through the browser.
❖ IndexedDB API is basically an object store that can be used to store and manipulate data on the client-
Fo
side.
❖ A native application also called as native app is an application program that is built for a particular device
or platform. 54