0% found this document useful (0 votes)
28 views192 pages

WT 9

Uploaded by

manabideka19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views192 pages

WT 9

Uploaded by

manabideka19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 192

Web Technology

HTML5
Introduction

• HTML5 is a technology markup language of the Internet, used for


structuring and presenting content for the World Wide Web.
• HTML5 is standardized in October 2014.
• The core aim of HTML5 is to improve the language with support for the
latest multimedia while keeping it easily readable by humans and
consistently understood by computers and devices (web browsers, parsers,
etc.).
• HTML5 adds many new syntactic features. These include the new <video>,
<audio> and <canvas> elements, as well as the integration of scalable vector
graphics (SVG) content (replacing generic <object> tags), and MathML for
mathematical formulas.
• Other new elements, such as <section>, <article>, <header> and <nav>, are
designed to enrich the semantic content of documents.
• New attributes have been introduced for the same purpose, while some
elements and attributes have been removed.
• Some elements, such as <a>, <cite> and <menu> have been changed,
redefined or standardized.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 2


Examples of New HTML5 Elements

• New semantic elements :


– <header>
– <footer>
– <article>
– <section>.
• New form control attributes :
– number
– date
– time
– calendar
– range.
• New graphic elements: <svg> and <canvas>.
• New multimedia elements: <audio> and <video>.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 3


New HTML5 API's (Application Programming Interfaces)

• The most interesting new API's are:


– HTML Geolocation
– HTML Drag and Drop
– HTML Local Storage (Store Data locally within users browser)
– HTML Application Cache (Offline Version of WebApplication)
– HTML Web Workers (JavaScript in Background))
– HTML SSE (Server Sent Events)

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 4


Elements Removed in HTML5

• The following HTML4 elements have been removed from HTML5:

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 5


HTML5 Browser Support

• HTML5 is supported in all modern browsers.


• In addition, all browsers, old and new, automatically handle unrecognized
elements as inline elements.
• Because of this, we can "teach" old browsers to handle "unknown" HTML
elements.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 6


Define DOCTYPE declaration

• The Doc type declaration is very simple:



For HTML5:
• <!DOCTYPE html>
• For HTML4:
– HTML 4.01 Strict
– <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
– HTML 4.01 Transitional
– <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 7


Define Character Set

• The character encoding (charset) declaration is also very simple:



For HTML5:
• <meta charset="UTF-8">
• For HTML4:
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">

• The default character encoding in HTML5 is UTF-8.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 8


Define HTML5 Elements as Block Elements

• HTML5 defines 8 new semantic HTML elements.


– All these are block level elements.
• To secure correct behavior in older browsers, we can set the CSS
display property to block:
Example

header, section, footer, aside, nav, main, article, figure {


display: block;
}

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 9


Adding New Elements to HTML

• we can add any new element to HTML with a browser trick:


• This example adds a new element called <ISTGU> to HTML, and
defines a display style for it:
<!DOCTYPE html>
<html>
<head>
<title>Creating an HTML Element</title>
<script>document.createElement(" ISTGU ")</script>
<style>
ISTGU{ display: block; background-color: #ddd; padding: 50px; font-size: 30px;
}
</style>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
< ISTGU >My First Hero</ ISTGU >
</body>
</html>
EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 10


Problem With Internet Explorer

• We can use the method of previous example, for all new HTML5
elements, but Internet Explorer 8 and earlier, does not allow styling of
unknown elements.

• Sjoerd Visscher created the "HTML5 Enabling JavaScript", named as


"the shiv":

<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

The code above is a comment, but versions previous to IE9 will read it (and
understand it).
The link to the shiv code must be placed in the <head> element, because
Internet Explorer needs to know about all new elements before reading them.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 11


An HTML5 Skeleton

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 12


HTML5 New Elements

New Semantic/Structural Elements

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 13


Contd..

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 14


HTML5 New Form Elements

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 15


HTML5 New Input Types

New Input Types New Input Attributes


 color  number  autocomplete  autocomplete
 date  range  autofocus  autofocus
 datetime  search  form  form
 datetime-local  tel  formaction  formaction
 email  time  formenctype  formenctype
 month  url  formmethod  formmethod
 week  formnovalidate  formnovalidate
 formtarget  formtarget
 height and width  height and
width

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 16


HTML5 - New Attribute Syntax

• HTML5 allows 4 different syntaxes for attributes.


• This example demonstrates the different syntaxes used in an <input>
tag:

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 17


HTML5 Graphics

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 18


New Media Elements

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 19


HTML5 Semantic Elements

• Semantics is the study of the meanings of words and phrases in


language.
• A semantic element clearly describes its meaning to both the browser
and the developer.
– Examples of non-semantic elements: <div> and <span> - Tells
nothing about its content.
– Examples of semantic elements: <form>, <table>, and <img> -
Clearly defines its content.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 20


Why Semantic HTML5 Elements?

• With HTML4, developers used their own favorite attribute names to


style page elements:
• header, top, bottom, footer, menu, navigation, main, container, content,
article, sidebar, top, nav, ...
• This made it impossible for search engines to identify the correct web
page content.
• With HTML5 elements like: <header> <footer> <nav> <section>
<article>, this will become easier.
• According to the W3C, a Semantic Web:
• "Allows data to be shared and reused across applications, enterprises,
and communities."

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 21


Contd..

• <article>
• <aside>
• <details>
• <figcaption>
• <figure>
• <header>
• <footer>
• <main>
• <mark>
• <nav>
• <section>
• <summary>
• <time>

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 22


HTML5 <article> Element

• The <article> element specifies independent, self-contained content.


• An article should make sense on its own, and it should be possible to read it
independently from the rest of the web site.
• Examples of where an <article> element can be used:
– Forum post
– Blog post
– Newspaper article
Default CSS Settings
• Most browsers will display the <article> element with the following default
values:
article {
display: block;
}

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 23


HTML5 <aside> Element

• The <aside> element defines some content aside from the content it is
placed in (like a sidebar).
• The aside content should be related to the surrounding content.
• The <aside> content could be placed as a sidebar in an article.
Default CSS Settings
• Most browsers will display the <aside> element with the following
default values:
aside{
display: block;
}

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 24


HTML <details> Tag

• The <details> tag specifies additional details that the user can view or
hide on demand.
• The <details> tag can be used to create an interactive widget that the
user can open and close. Any sort of content can be put inside the
<details> tag.
• The content of a <details> element should not be visible unless the open
attribute is set.
• The <summary> tag is used to specify a visible heading for the details.
The heading can be clicked to view/hide the details.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 25


Contd..

Default CSS Settings


• Most browsers will display the <details> element with the following
default values:
details {
display: block;
}

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 26


HTML <summary> Tag

• The <summary> tag defines a visible heading for the <details> element.
The heading can be clicked to view/hide the details.
• Default CSS Settings
Most browsers will display the <summary> element with the following
default values:
summary {
display: block;
}

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 27


HTML5 <figcaption> Elements

• The <figcaption> tag defines a caption for a <figure> element.


• The <figcaption> element can be placed as the first or last child of the
<figure> element.
Default CSS Settings
• Most browsers will display the < figcaption > element with the
following default values:
figcaption{
display: block;
}

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 28


HTML5 <figure> Tag

• The <figure> tag specifies self-contained content, like illustrations,


diagrams, photos, code listings, etc.
Default CSS Settings
• Most browsers will display the <figure> element with the following
default values:
figure {
display: block;
margin-top: 1em;
margin-bottom: 1em;
margin-left: 40px;
margin-right: 40px;
}

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 29


HTML5 <header> Element

• The <header> element represents a container for introductory content or


a set of navigational links.
• A <header> element typically contains:
– one or more heading elements (<h1> - <h6>)
– logo or icon
– authorship information
• We can have several <header> elements in one document.
• A <header> tag cannot be placed within a <footer>, <address> or
another <header> element.
Default CSS Settings
• Most browsers will display the <header> element with the following
default values:
header {
display: block;
}

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 30
HTML5 <footer> Element

• The <footer> element specifies a footer for a document or section.


• A <footer> element should contain information about its containing
element.
• A <footer> element typically contains:
– authorship information
– copyright information
– contact information
– sitemap
– back to top links
– related documents
• We can have several <footer> elements in one document.
Default CSS Settings
• Most browsers will display the <footer> element with the following default
values:
footer {
display: block;
}
EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 31


HTML <main> Tag

• The <main> tag specifies the main content of a document.


• The content inside the <main> element should be unique to the
document. It should not contain any content that is repeated across
documents such as sidebars, navigation links, copyright information,
site logos, and search forms.
• Note: There must not be more than one <main> element in a document.
The <main> element must NOT be a descendant of an <article>,
<aside>, <footer>, <header>, or <nav> element.

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 32


HTML <mark> Tag

• The <mark> tag defines marked text.


• Use the <mark> tag if you want to highlight parts of your text
• Default CSS Settings
• Most browsers will display the <mark> element with the following
default values:
mark {
background-color: yellow;
color: black;
}

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 33


HTML5 <nav> Element

• The <nav> tag defines a set of navigation links.


• Notice that NOT all links of a document should be inside a <nav>
element.
• The <nav> element is intended only for major block of navigation
links.
Default CSS Settings
• Most browsers will display the <nav> element with the following
default values:
nav {
display: block;
}

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 34


HTML5 <section> Element

• The <section> tag defines sections in a document, such as chapters,


headers, footers, or any other sections of the document.
• A Web site's home page could be split into sections for introduction,
content, and contact information.
• Default CSS Settings
• Most browsers will display the <section> element with the following
default values:
section {
display: block;
}

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 35


HTML <time> Tag

• The <time> tag defines a human-readable date/time.


• This element can also be used to encode dates and times in a machine-
readable way so that user agents can offer to add birthday reminders or
scheduled events to the user's calendar, and search engines can produce
smarter search results.
• Default CSS Settings
– None.

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 36


HTML <time> datetime Attribute

• The datetime attribute represent the machine-readable date/time of the


<time> element.
• Syntax
<time datetime="YYYY-MM-DDThh:mm:ssTZD">

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 37


Contd..

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 38


Example
Dates:
<time datetime="1914"> <!-- means the year 1914 -->
<time datetime="1914-12"> <!-- means December 1914 -->
<time datetime="1914-12-20"> <!-- means 20 December 1914 -->
<time datetime="12-20"> <!-- means 20 December any year -->
<time datetime="1914-W15"> <!-- means week 15 of year 1914 -->
Date and Times:
<time datetime="1914-12-20T08:00"> <!-- means 20 December 1914 at 8am -->
<time datetime="1914-12-20 08:00"> <!-- also means 20 December 1914 at 8am -->
<time datetime="1914-12-20 08:30:45"> <!-- with minutes and seconds -->
<time datetime="1914-12-20 08:30:45.687"> <!-- with minutes, seconds, and milliseconds -->
Times:
<time datetime="08:00"> <!-- means 8am -->
<time datetime="08:00-03:00"> <!-- means 8am in Rio de Janeiro (UTC-3 hours) -->
<time datetime="08:00+03:00"> <!-- means 8am in Madagascar (UTC+3 hours) -->
Durations:
<time datetime="P2D"> <!-- means a duration of 2 days -->
<time datetime="PT15H10M"> <!-- means a duration of 15 hours and 10 minutes -->

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 39


HTML <address> Tag

• The <address> tag defines the contact information for the author/owner of a
document or an article.
• If the <address> element is inside the <body> element, it represents contact
information for the document.
• If the <address> element is inside an <article> element, it represents contact
information for that article.
• The text in the <address> element usually renders in italic. Most browsers will add a
line break before and after the address element.
• The <address> tag should NOT be used to describe a postal address, unless it is a
part of the contact information.
• The <address> element will typically be included along with other information in a
<footer> element.
Default CSS Settings
• Most browsers will display the <address> element with the following default values:
address {
display: block;
font-style: italic;
}

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 40


HTML <menuitem> Tag

• The <menuitem> tag defines a command/menu item that the user can
invoke from a popup menu.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 41


Attributes of <manuitem>

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 42


HTML <menuitem> checked Attribute

• The checked attribute is a boolean attribute.


• When present, it specifies that the <menuitem> element should be
checked (pre-selected) when the page loads.
<menuitem checked>

• Note: This attribute can only be used if type="checkbox" or


type="radio"

• <menu type="popup">
<menuitem type="radio" radiogroup="alignment" checked
label="Left" onclick="setAlign('left')">
</menu>

• Currently no browser support this attribute

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 43


HTML <menuitem> default Attribute

• The default attribute is a boolean attribute.


• When present, it specifies that the <menuitem> element should be the
default command.
<menuitem default>
• <menu>
<menuitem command="submitbutton" default>
</menu>

• Currently no browser support this attribute

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 44


HTML <menuitem> disabled Attribute

• The disabled attribute is a boolean attribute.


• When present, it specifies that the <menuitem> element should be
disabled.
<menuitem disabled>
• <menu type="context" id="mymenu">
<menuitem label="Refresh" icon="ico_reload.png"
disabled></menuitem>
<menuitem label="Twitter" icon="ico_twitter.png"></menuitem>
<menuitem label="Facebook" icon="ico_facebook.png"></menuitem>
</menu>

• Only Firefox browser support this attribute

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 45


HTML <menuitem> icon Attribute

• The icon attribute specifies an image that represents the command/menu


item.
<menuitem icon="URL">
• <menu type="context" id="mymenu">
<menuitem label="Refresh" icon="ico_reload.png"></menuitem>
<menuitem label="Twitter" icon="ico_twitter.png"></menuitem>
<menuitem label="Facebook" icon="ico_facebook.png"></menuitem>
</menu>

• Only Firefox browser support this attribute

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 46


HTML <menuitem> label Attribute

• The required label attribute specifies the name of the command/menu


item, as shown to the user.
<menuitem label="text">

• <menu type="context" id="mymenu">


<menuitem label="Refresh"></menuitem>
<menuitem label="Twitter"></menuitem>
<menuitem label="Facebook"></menuitem>
</menu>

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 47


HTML <menuitem> radiogroup Attribute

• The radiogroup attribute specifies the name of the group of command


that will be toggled when the command/menu item itself is
activated/toggled.
<menuitem radiogroup="groupname">
• Note: This attribute can only be used if type="radio".
• <menu>
<menuitem type="radio" label="Left" radiogroup="alignment"
onclick="setAlign('left')">Left</menuitem>
</menu>

• Currently no browser support this attribute

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 48


HTML <menuitem> type Attribute

<menuitem type="command|checkbox|radio"
• The type attribute specifies the type of command/menu item.
• <menu>
<menuitem type="command" label="Save"
onclick="save()">Save</menuitem>
</menu>

• Currently no browser support this attribute

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 49


HTML <meter> Tag

• The <meter> tag defines a scalar measurement within a known range, or


a fractional value.
• This is also known as a gauge.
• Examples: Disk usage, the relevance of a query result, etc.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 50


HTML <meter> high,low,max,min Attribute

<meter high="number">
<meter low="number">
<meter max="number">
<meter min="number">
• The high attribute specifies the range where the gauge's value is considered to be a high value.
• The low attribute specifies the range where the gauge's value is considered to be a low value.
• The max attribute specifies the upper bound of the gauge.
• The min attribute specifies the lower bound of the gauge.
• The high attribute value must be less than the max attribute value, and it also must be greater
than the low and min attribute values.
• The low attribute value must be greater than the min attribute value, and it also must be less than
the high and max attribute values.
• The max attribute value must be greater than the min attribute value. If unspecified, the default
value is 1.
• The min attribute value must be less than the max attribute value. If unspecified, the default
value is 0.

• <meter min="0" low="40" high="90" max="100" value="95"></meter>

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 51


HTML <meter> optimum Attribute

• The optimum attribute specifies the range where the gauge's value is
considered to be an optimal value.
<meter optimum="number">
• number, Specifies a floating point number that is the optimal value of
the gauge

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 52


HTML <meter> value Attribute

• The required value attribute specifies the current, or "measured", value


of the gauge.
• The value attribute must be between the min and max attribute values.
<meter value="number">
• number, Specifies a floating point number that is the current value of
the gauge

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 53


HTML <progress> Tag

• The <progress> tag represents the progress of a task.


• Use the <progress> tag in conjunction with JavaScript to display the
progress of a task
<progress value="22" max="100"></progress>

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 54


HTML <wbr> Tag

• <wbr> Word Break Opportunity


• The <wbr> element to add word break opportunities.
• <p>
To learn AJAX, you must be familiar with the
XML<wbr>Http<wbr>Request Object.
</p>

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 55


HTML <bdi> Tag

• bdi stands for Bi-directional Isolation.


• The <bdi> tag isolates a part of text that might be formatted in a different
direction from other text outside it.
• This element is useful when embedding user-generated content with an
unknown directionality.
• <ul>
<li>Hori <bdi>hrefs</bdi>: 60 points</li>
<li>Zodu <bdi>jdoe</bdi>: 80 points</li>
<li>Modhu<bdi‫<<إيان‬/bdi>: 90 points</li>
</ul>

• In the example, usernames are shown along with the number of points in an
exam.
• If the <bdi> element is not supported in the browser, the username of the
Arabic user would confuse the text (the bidirectional algorithm would put
the colon and the number "6" next to the word "User" rather than next to the
word "points").
EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 56


HTML <datalist> Tag

• The <datalist> tag specifies a list of pre-defined options for an <input>


element.
• The <datalist> tag is used to provide an "autocomplete" feature on
<input> elements. Users will see a drop-down list of pre-defined
options as they input data.
• Use the <input> element's list attribute to bind it together with a
<datalist> element.
Default CSS Settings
• Most browsers will display the <datalist> element with the following
default values:
datalist {
display: none;
}

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 57


Migration from HTML4 to HTML5

HTML4 EXAMPLE HTML5 EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 58


HTML(5) Style Guide and Coding Conventions

• Use Correct Document Type


• Always declare the document type as the first line in your document:
<!DOCTYPE html>
• Use Lower Case Element Names
• HTML5 allows mixing uppercase and lowercase letters in element
names.
– It is recommend to use lowercase element names:
– Mixing uppercase and lowercase names is bad
– Developers are used to use lowercase names (as in XHTML)
– Lowercase look cleaner
– Lowercase are easier to write

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 59


Contd..

• Bad:
<SECTION>
<p>This is a paragraph.</p>
</SECTION>
• Very Bad:
<Section>
<p>This is a paragraph.</p>
</SECTION>
• Good:
<section>
<p>This is a paragraph.</p>
</section>

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 60


Contd..

• Close All HTML Elements


• In HTML5, you don't have to close all elements (for example the <p>
element).
• It is recommend to close all HTML elements:
• Looking bad:
<section>
<p>This is a paragraph.
<p>This is a paragraph.
</section>
• Looking good:
<section>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</section>

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 61


Contd..

• Close Empty HTML Elements


• In HTML5, it is optional to close empty elements.
• This is allowed:
<meta charset="utf-8">
• This is also allowed:
<meta charset="utf-8" />
• The slash (/) is required in XHTML and XML.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 62


Contd..

• Use Lower Case Attribute Names


• HTML5 allows mixing uppercase and lowercase letters in attribute
names.
• It is recommend to use lowercase attribute names:
• Mixing uppercase and lowercase names is bad
• Developers are used to use lowercase names (as in XHTML)
• Lowercase look cleaner
• Lowercase are easier to write
• Looking bad:
<div CLASS="menu">
• Looking good:
<div class="menu">

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 63


Contd..

• Quote Attribute Values


• HTML5 allows attribute values without quotes.
• It is recommend to use quoting attribute values:
• We have to use quotes if the value contains spaces
• Mixing styles is never good
• Quoted values are easier to read
• This will not work, because the value contains spaces:
<table class=table stop>
• This will work:
<table class="table stop">

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 64


Contd..

• Image Attributes
• Always use the alt attribute with images. It is important when the image
cannot be viewed.
<img src="html5.gif" alt="HTML5" style="width:128px;height:128px">
• Always define image size.
• It reduces flickering because the browser can reserve space for images
before they are loaded.
<img src="html5.gif" alt="HTML5" style="width:128px;height:128px">

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 65


Contd..

Spaces and Equal Signs


• Spaces around equal signs is legal:
<link rel = "stylesheet" href = "styles.css">
• But space-less is easier to read, and groups entities better together:
<link rel="stylesheet" href="styles.css">
Blank Lines and Indentation
• Do not add blank lines without a reason.
• For readability, add blank lines to separate large or logical code blocks.
• For readability, add 2 spaces of indentation. Do not use TAB.
• Do not use unnecessary blank lines and indentation.
• It is not necessary to use blank lines between short and related items. It
is not necessary to indent every element:

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 66


Contd..

Omitting <html> and <body>?


• In the HTML5 standard, the <html> tag and the <body> tag can be
omitted.
• The following code will validate as HTML5:
<!DOCTYPE html>
<head>
<title>Page Title</title>
</head>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

But it is not recommend to omit the <html> and <body> tags.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 67


Contd..

• Omitting <head>?
• In the HTML5 standard, the <head> tag can also be omitted.
• By default, browsers will add all elements before <body>, to a default
<head> element.
<!DOCTYPE html>
<html>
<title>Page Title</title>

<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>

</html>

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 68


Contd..

HTML Comments
• Short comments should be written on one line, with a space after <!--
and a space before -->:
<!-- This is a comment -->
• Long comments, spanning many lines, should be written with <!-- and
--> on separate lines:
<!--
This is a long comment example. This is a long comment example.
This is a long comment example.
This is a long comment example. This is a long comment example.
This is a long comment example.
-->
• Long comments are easier to observe, if they are indented 2 spaces.
• File Extensions
– HTML files should have a .html extension (not .htm).

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 69


HTML5 Canvas

• The HTML <canvas> element is used to draw graphics, on the fly, via
scripting (usually JavaScript).
• The <canvas> element is only a container for graphics.
• We need to use a script to actually draw the graphics.
• Canvas has several methods for drawing paths, boxes, circles, text, and
adding images.
• A canvas is a rectangular area on an HTML page.
• By default, a canvas has no border and no content.
Syntax
<canvas id="myCanvas" width="200" height="100"></canvas>
• Note: Always specify an id attribute (to be referred to in a script), and a
width and height attribute to define the size of the canvas.
• To add a border, use the style attribute:

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 70


Canvas Contd..

• HTML Canvas Can Draw Text


– Canvas can draw colorful text, with or without animation.
• HTML Canvas Can Draw Graphics
– Canvas has great features for graphical data presentation with an
imagery of graphs and charts.
• HTML Canvas Can be Animated
– Canvas objects can move. Everything is possible: from simple
bouncing balls to complex animations.
• HTML Canvas Can be Interactive
– Canvas can respond to JavaScript events.
– Canvas can respond to any user action (key clicks, mouse clicks,
button clicks, finger movement).
• HTML Canvas Can be Used in Games
– Canvas' methods for animations, offer a lot of possibilities for
HTML gaming applications.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 71


HTML Canvas Drawing

• Draw on the Canvas With JavaScript


– All drawing on the HTML canvas must be done with JavaScript:
Step 1: Find the Canvas Element
• First, find the <canvas> element.
var canvas = document.getElementById("myCanvas");
Step 2: Create a Drawing Object
• Secondly, we need a drawing object for the canvas.
• The getContext() is a built-in HTML object, with properties and
methods for drawing:
var ctx = canvas.getContext("2d");

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 72


Contd..

Step 3: Draw on the Canvas


• Finally, we can draw on the canvas.
• Set the fill style of the drawing object to the color red:
ctx.fillStyle = "#FF0000";
• The fillStyle property can be a CSS color, a gradient, or a pattern.
• The default fillStyle is black.
• The fillRect(x,y,width,height) method draws a rectangle, filled with the
fill style, on the canvas:
ctx.fillRect(0,0,150,75);

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 73


HTML Canvas Coordinates

Canvas Coordinates
• The HTML canvas is a two-dimensional grid.
• The upper-left corner of the canvas has the coordinates (0,0)
• In our previous example we used: fillRect(0,0,150,75).
• This means: Start at the upper-left corner (0,0) and draw a 150x75
pixels rectangle.

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 74


Contd..

Draw a Line
• To draw a straight line on a canvas, use the following methods:
• moveTo(x,y) - defines the starting point of the line
• lineTo(x,y) - defines the ending point of the line
• To actually draw the line, we must use one of the "ink" methods, like
stroke().
• Define a starting point in position (0,0), and an ending point in position
(200,100). Then use the stroke() method to actually draw the line:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 75


Contd..

Draw a Circle
• To draw a circle on a canvas, use the following methods:
– beginPath();
– arc(x,y,r,start,stop)
• Define a circle with the arc() method. Then use the stroke() method to
actually draw the circle:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 76


HTML5 Canvas Gradients

Canvas - Gradients
• Gradients can be used to fill rectangles, circles, lines, text, etc.
• Shapes on the canvas are not limited to solid colors.
• There are two different types of gradients:
– createLinearGradient(x,y,x1,y1) - creates a linear gradient
– createRadialGradient(x,y,r,x1,y1,r1) - creates a radial/circular
gradient
• Once we have a gradient object, we must add two or more color stops.
• The addColorStop() method specifies the color stops, and its position
along the gradient.
• Gradient positions can be anywhere between 0 to 1.
• To use the gradient, set the fillStyle or strokeStyle property to the
gradient, then draw the shape (rectangle, text, or a line).

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 77


Using createLinearGradient()

Example
• Create a linear gradient. Fill rectangle with the gradient:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

// Create gradient
var grd=ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");

// Fill with gradient


ctx.fillStyle=grd;
ctx.fillRect(10,10,150,80);

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 78


Using createRadialGradient():

• Create a radial/circular gradient. Fill rectangle with the gradient:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

// Create gradient
var grd=ctx.createRadialGradient(75,50,5,90,60,100);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");

// Fill with gradient


ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 79


HTML Canvas Text

• Drawing Text on the Canvas


• To draw text on a canvas, the most important property and methods are:
– font - defines the font properties for the text
– fillText(text,x,y) - draws "filled" text on the canvas
– strokeText(text,x,y) - draws text on the canvas (no fill)

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 80


Using fillText()

• Example
• Set font to 30px "Arial" and write a filled text on the canvas:

var canvas = document.getElementById("myCanvas");


var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 81


Using strokeText()

• Example
• Set font to 30px "Arial" and write a text, with no fill, on the canvas:

var canvas = document.getElementById("myCanvas");


var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World",10,50);

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 82


Add Color and Center Text

• Example
• Set font to 30px "Comic Sans MS" and write a filled red text in the
center of the canvas:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("Hello World", canvas.width/2, canvas.height/2);

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 83


HTML Canvas Images

• Canvas - Images
• To draw an image on a canvas, use the following method:
– drawImage(image,x,y)

window.onload() function () {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 10, 10);
}

• We cannot draw the image before the image has loaded. Call the
function from window.onload().

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 84


Canvas Image 2

var canvas = document.getElementById('myCanvas');


var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.src = 'canvas.png';
context.drawImage(imageObj, 69, 50);

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 85


HTML canvas translate() Method

• The translate() method remaps the (0,0) position on the canvas.


• JavaScript syntax: context.translate(x,y);
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillRect(10,10,100,50);
ctx.translate(70,70);
ctx.fillRect(10,10,100,50);

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 86


HTML canvas rotate() Method

• The rotate() method rotates the current drawing.


• JavaScript syntax: context.rotate(angle);
• angle The rotation angle, in radians.
• To calculate from degrees to radians: degrees*Math.PI/180.
Example: to rotate 5 degrees, specify the following: 5*Math.PI/180

• var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rotate(20*Math.PI/180);
ctx.fillRect(50,20,100,50);

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 87
Canvas Clock
• An analog clock using HTML canvas
Part I - Create the Canvas
• The clock needs an HTML container. Create an 300 x 300 pixel HTML canvas:

<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="300" height="300" style="background-color:#333"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var radius = canvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.90
drawClock();
function drawClock() {
ctx.arc(0, 0, radius, 0 , 2*Math.PI);
ctx.fillStyle = "white";
ctx.fill();
}
</script>
</body>
</html>
EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 88


Code Explained

• Add an HTML <canvas> element to your page:


<canvas id="myCanvas" width="300" height="300" style="background-color:#333"></canvas>

• Create a canvas object (var canvas) from the HTML canvas element:
var canvas = document.getElementById("canvas");
• Create a 2d drawing object (var ctx) for the canvas object:
var ctx = canvas.getContext("2d");
• Calculate the clock radius, using the height of the canvas:
var radius = canvas.height / 2;
• Using the canvas height to calculate the clock radius, makes the clock
work for all canvas sizes.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 89


Contd..

• Remap the (0,0) position (of the drawing object) to the center of the
canvas:
ctx.translate(radius, radius);
• Reduce the clock radius (to 90%) to draw the clock well inside the
canvas:
radius = radius * 0.90;
• Create a function to draw the clock:
function drawClock() {
ctx.arc(0, 0, radius, 0 , 2*Math.PI);
ctx.fillStyle = "white";
ctx.fill();
}

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 90


Canvas Clock Face

• Part II - Draw a Clock Face


• The clock needs a clock face. Create a JavaScript function to draw a
clock face:
function drawClock() {
drawFace(ctx, radius);
}
function drawFace(ctx, radius) {
var grad;
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2*Math.PI);
ctx.fillStyle = 'white';
ctx.fill();
grad = ctx.createRadialGradient(0,0,radius*0.95, 0,0,radius*1.05);
grad.addColorStop(0, '#333');
grad.addColorStop(0.5, 'white');
grad.addColorStop(1, '#333');
ctx.strokeStyle = grad;
ctx.lineWidth = radius*0.1;
ctx.stroke();
ctx.beginPath();
ctx.arc(0, 0, radius*0.1, 0, 2*Math.PI);
ctx.fillStyle = '#333';
ctx.fill();
} EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 91
Code Explained

• Create a drawFace() function for drawing the clock face:


function drawClock() {
drawFace(ctx, radius);
}

function drawFace(ctx, radius) {


}
Draw the white circle:
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2*Math.PI);
ctx.fillStyle = 'white';
ctx.fill();

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 92


Contd..

• Create a radial gradient (95% and 105% of original clock radius):


grad = ctx.createRadialGradient(0,0,radius*0.95, 0,0,radius*1.05);
• Create 3 color stops, corresponding with the inner, middle, and outer
edge of the arc:
grad.addColorStop(0, '#333');
grad.addColorStop(0.5, 'white');
grad.addColorStop(1, '#333');
• The color stops create a 3D effect.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 93


Contd..

• Define the gradient as the stroke style of the drawing object:


ctx.strokeStyle = grad;
• Define the line with of the drawing object (10% of radius):
ctx.lineWidth = radius * 0.1;
• Draw the circle:
ctx.stroke();
• Draw the clock center:
ctx.beginPath();
ctx.arc(0, 0, radius*0.1, 0, 2*Math.PI);
ctx.fillStyle = '#333';
ctx.fill();

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 94


Draw Clock Numbers
• The clock needs numbers. Create a JavaScript function to draw clock numbers:
function drawClock() {
drawFace(ctx, radius);
drawNumbers(ctx, radius);
}
function drawNumbers(ctx, radius) {
var ang;
var num;
ctx.font = radius*0.15 + "px arial";
ctx.textBaseline="middle";
ctx.textAlign="center";
for(num= 1; num < 13; num++){
ang = num * Math.PI / 6;
ctx.rotate(ang);
ctx.translate(0, -radius*0.85);
ctx.rotate(-ang);
ctx.fillText(num.toString(), 0, 0);
ctx.rotate(ang);
ctx.translate(0, radius*0.85);
ctx.rotate(-ang);
}
}

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 95
Example Explained

• Set the font size (of the drawing object) to 15% of the radius:
ctx.font = radius*0.15 + "px arial";
• Set the text alignment to the middle and the center of the print position:
ctx.textBaseline="middle";
ctx.textAlign="center";
• Calculate the print position (for 12 numbers) to 85% of the radius, rotated
(PI/6) for each number:
for(num= 1; num < 13; num++) {
ang = num * Math.PI / 6;
ctx.rotate(ang);
ctx.translate(0, -radius*0.85);
ctx.rotate(-ang);
ctx.fillText(num.toString(), 0, 0);
ctx.rotate(ang);
ctx.translate(0, radius*0.85);
ctx.rotate(-ang);
}

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 96


Draw Clock Hands
• The clock needs hands. Create a JavaScript function to draw clock hands:
function drawClock() {
drawFace(ctx, radius);
drawNumbers(ctx, radius);
drawTime(ctx, radius);
}
function drawTime(ctx, radius){
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
//hour
hour=hour%12;
hour=(hour*Math.PI/6)+(minute*Math.PI/(6*60))+(second*Math.PI/(360*60));
drawHand(ctx, hour, radius*0.5, radius*0.07);
//minute
minute=(minute*Math.PI/30)+(second*Math.PI/(30*60));
drawHand(ctx, minute, radius*0.8, radius*0.07);
// second
second=(second*Math.PI/30);
drawHand(ctx, second, radius*0.9, radius*0.02);
}
function drawHand(ctx, pos, length, width) {
ctx.beginPath();
ctx.lineWidth = width;
ctx.lineCap = "round";
ctx.moveTo(0,0);
ctx.rotate(pos);
ctx.lineTo(0, -length);
ctx.stroke();
ctx.rotate(-pos);
}

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 97
Example Explained

• Use Date to get hour, minute, second:


var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
• Calculate the angle of the hour hand, and draw it a length (50% of
radius), and a width (7% of radius):
hour=hour%12;
hour=(hour*Math.PI/6)+(minute*Math.PI/(6*60))+(second*Math.PI/
(360*60));
drawHand(ctx, hour, radius*0.5, radius*0.07);
• Use the same technic for minutes and seconds.
• The drawHand() routine does not need an explanation. It just draws a
line with a given length and width.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 98


Start the Clock

• To start the clock, call the drawClock function at intervals:


var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var radius = canvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.90
//drawClock();
setInterval(drawClock, 1000);

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 99
Example Explained

• The only thing you have to do (to start the clock) is to call the
drawClock function at intervals.
Substitute:
• drawClock();

With:
• setInterval(drawClock, 1000);
• The interval is in milliseconds. drawClock will be called for each 1000
milliseconds.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 100


HTML5 SVG

• SVG stands for Scalable Vector Graphics


• SVG defines vector-based graphics in XML format.
• SVG is used to define vector-based graphics for the Web
• SVG graphics do NOT lose any quality if they are zoomed or resized
• Every element and every attribute in SVG files can be animated
• SVG is a W3C recommendation
• SVG integrates with other W3C standards such as the DOM and XSL
SVG is a W3C Recommendation
• SVG 1.0 became a W3C Recommendation on 4 September 2001.
• SVG 1.1 became a W3C Recommendation on 14 January 2003.
• SVG 1.1 (Second Edition) became a W3C Recommendation on 16
August 2011.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 101


Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 102
SVG Advantages

• Advantages of using SVG over other image formats (like JPEG and
GIF) are:
• SVG images can be created and edited with any text editor
• SVG images can be searched, indexed, scripted, and compressed
• SVG images are scalable
• SVG images can be printed with high quality at any resolution
• SVG images are zoomable (and the image can be zoomed without
degradation)
• SVG is an open standard
• SVG files are pure XML
• The main competitor to SVG is Flash.
• The biggest advantage SVG has over Flash is the compliance with other
standards (e.g. XSL and the DOM). Flash relies on proprietary
technology that is not open source.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 103


SVG Syntax

<svg width="100" height="100">


<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
• An SVG image begins with an <svg> element
• The width and height attributes of the <svg> element define the width and
height of the SVG image
• The <circle> element is used to draw a circle
• The cx and cy attributes define the x and y coordinates of the center of the
circle. If cx and cy are omitted, the circle's center is set to (0, 0)
• The r attribute defines the radius of the circle
• The stroke and stroke-width attributes control how the outline of a shape
appears. We set the outline of the circle to a 4px green "border"
• The fill attribute refers to the color inside the circle. We set the fill color to
yellow
• The closing </svg> tag closes the SVG image
• Note: Since SVG is written in XML, all elements must be properly closed!

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 104
SVG Shapes

• SVG has some predefined shape elements that can be used by


developers:
– Rectangle <rect>
– Circle <circle>
– Ellipse <ellipse>
– Line <line>
– Polyline <polyline>
– Polygon <polygon>
– Path <path>
• The following chapters will explain each element, starting with the rect
element.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 105


SVG Rectangle - <rect>

• The <rect> element is used to create a rectangle and variations of a


rectangle shape:
<svg width="400" height="110">
<rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
</svg>
• The width and height attributes of the <rect> element define the height
and the width of the rectangle
• The style attribute is used to define CSS properties for the rectangle
• The CSS fill property defines the fill color of the rectangle
• The CSS stroke-width property defines the width of the border of the
rectangle
• The CSS stroke property defines the color of the border of the rectangle

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 106
Other <rect> Example
• <svg width="400" height="180">
<rect x="50" y="20" width="150" height="150“ style="fill:blue;stroke:pink;stroke-width:5;fill-opacity:0.1;stroke-opacity:0.9" />
</svg>
• The x attribute defines the left position of the rectangle (e.g. x="50" places the
rectangle 50 px from the left margin)
• The y attribute defines the top position of the rectangle (e.g. y="20" places the
rectangle 20 px from the top margin)
• The CSS fill-opacity property defines the opacity of the fill color (legal range: 0
to 1)
• The CSS stroke-opacity property defines the opacity of the stroke color (legal
range: 0 to 1)

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 107
Other <rect> Example

• <svg width="400" height="180">


<rect x="50" y="20" width="150" height="150"
style="fill:blue;stroke:pink;stroke-width:5;opacity:0.5" />
</svg>
• The CSS opacity property defines the opacity value for the whole
element (legal range: 0 to 1)

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 108
Other <rect> Example

• <svg width="400" height="180">


<rect x="50" y="20" rx="20" ry="20" width="150" height="150"
style="fill:red;stroke:black;stroke-width:5;opacity:0.5" />
</svg>
• The rx and the ry attributes rounds the corners of the rectangle

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 109
SVG Circle - <circle>

• The <circle> element is used to create a circle:


• <svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
• The cx and cy attributes define the x and y coordinates of the center of
the circle. If cx and cy are omitted, the circle's center is set to (0,0)
• The r attribute defines the radius of the circle

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 110
SVG Ellipse - <ellipse>

• The <ellipse> element is used to create an ellipse.


• An ellipse is closely related to a circle. The difference is that an ellipse
has an x and a y radius that differs from each other, while a circle has
equal x and y radius:
• <svg height="140" width="500">
<ellipse cx="200" cy="80" rx="100" ry="50"
style="fill:yellow;stroke:purple;stroke-width:2" />
</svg>
• The cx attribute defines the x coordinate of the center of the ellipse
• The cy attribute defines the y coordinate of the center of the ellipse
• The rx attribute defines the horizontal radius
• The ry attribute defines the vertical radius

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 111
Other <ellipse> example

• <svg height="150" width="500">


<ellipse cx="240" cy="100" rx="220" ry="30" style="fill:purple" />
<ellipse cx="220" cy="70" rx="190" ry="20" style="fill:lime" />
<ellipse cx="210" cy="45" rx="170" ry="15" style="fill:yellow" />
</svg>

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 112
Other <ellipse> example

• <svg height="100" width="500">


<ellipse cx="240" cy="50" rx="220" ry="30" style="fill:yellow" />
<ellipse cx="220" cy="50" rx="190" ry="20" style="fill:white" />
</svg>

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 113
SVG Line - <line>

• The
• <svg height="210" width="500">
<line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:2" />
</svg>
• <line> element is used to create a line:
• The x1 attribute defines the start of the line on the x-axis
• The y1 attribute defines the start of the line on the y-axis
• The x2 attribute defines the end of the line on the x-axis
• The y2 attribute defines the end of the line on the y-axis

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 114
SVG Polygon - <polygon>

• The <polygon> element is used to create a graphic that contains at least


three sides.
• Polygons are made of straight lines, and the shape is "closed" (all the
lines connect up).
• <svg height="210" width="500">
<polygon points="200,10 250,190 160,210" style="fill:lime;stroke:purple;stroke-width:1" />
</svg>
• The points attribute defines the x and y coordinates for each corner of
the polygon

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 115
Other <polygon> Example

• <svg height="250" width="500">


<polygon points="220,10 300,210 170,250 123,234" style="fill:lime;stroke:purple;stroke-width:1" />
</svg>

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 116
Other <polygon> Example

• <svg height="210" width="500">


<polygon points="100,10 40,198 190,78 10,78 160,198"
style="fill:lime;stroke:purple;stroke-width:5;fill-rule:nonzero;" />
</svg>

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 117
Other <polygon> Example

• <svg height="210" width="500">


<polygon points="100,10 40,198 190,78 10,78 160,198"
style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" />
</svg>

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 118
SVG Polyline - <polyline>

• The <polyline> element is used to create any shape that consists of only
straight lines:
<svg height="200" width="500">
<polyline points="20,20 40,25 60,40 80,120 120,140 200,180"
style="fill:none;stroke:black;stroke-width:3" />
</svg>

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 119
Other <polyline> Example

• <svg height="180" width="500">


<polyline points="0,40 40,40 40,80 80,80 80,120 120,120 120,160"
style="fill:white;stroke:red;stroke-width:4" />
</svg>

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 120
SVG Path - <path>

• The <path> element is used to define a path.


• The following commands are available for path data:
• M = moveto
• L = lineto
• H = horizontal lineto
• V = vertical lineto
• C = curveto
• S = smooth curveto
• Q = quadratic Bézier curve
• T = smooth quadratic Bézier curveto
• A = elliptical Arc
• Z = closepath
• Note: All of the commands above can also be expressed with lower
letters. Capital letters means absolutely positioned, lower cases means
relatively positioned.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 121


SVG Path - <path> Example

• The example below defines a path that starts at position 150,0 with a
line to position 75,200 then from there, a line to 225,200 and finally
closing the path back to 150,0:
• <svg height="210" width="400">
<path d="M150 0 L75 200 L225 200 Z" />
</svg>

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 122
SVG Text - <text>

• The <text> element is used to define a text.


• <svg height="30" width="200">
<text x="0" y="15" fill="red">I love SVG!</text>
</svg>

<svg height="60" width="200">


<text x="0" y="15" fill="red" transform="rotate(30 20,40)">I love SVG</text>
</svg>

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 123
Transform="rotate()” example

<!DOCTYPE html>
<html>
<body>

<svg height="200" width="200">


<text x="10" y="1" fill="red" transform="rotate(40)">I love SVG</text>

<rect x="20" y="70" width="40" height="40“ style="stroke: #3333cc; fill:none;“ />

<rect x="20" y="70" width="40" height="40“ style="fill: #3333cc“ transform="rotate(15, 40, 40)“ />
Sorry, your browser does not support inline SVG.
</svg>

</body>
</html>

• rotate(x, y, angle) or rotate(angle)

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 124
Example <text> <tspan>

• The <text> element can be arranged in any number of sub-groups with


the <tspan> element. Each <tspan> element can contain different
formatting and position.
• Text on several lines (with the <tspan> element):
<svg height="90" width="200">
<text x="10" y="20" style="fill:red;">Several lines:
<tspan x="10" y="45">First line.</tspan>
<tspan x="10" y="70">Second line.</tspan>
</text>
</svg>

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 125
Example <text> Text as a link

• Text as a link (with the <a> element):


<!DOCTYPE html>
<html>
<body>
<svg height="30" width="200" xmlns:xlink="http://www.w3.org/1999/xlink">
<a xlink:href="http://www.google.com" target="_blank">
<text x="0" y="15" fill="red">View Google</text>
</a>
Sorry, your browser does not support inline SVG.
</svg>
</body>
</html>

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 126
SVG Stroke Properties

• SVG offers a wide range of stroke properties.


– stroke
– stroke-width
– stroke-linecap
– stroke-dasharray
• All the stroke properties can be applied to any kind of lines, text and
outlines of elements like a circle.
• The stroke property defines the color of a line, text or outline of an
element:
<svg height="80" width="300">
<g fill="none">
<path stroke="red" d="M5 20 l215 0" />
<path stroke="blue" d="M5 40 l215 0" />
<path stroke="black" d="M5 60 l215 0" />
</g>
</svg>
• <g> for grouping related graphics elements

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 127
SVG stroke-width Property

• The stroke-width property defines the thickness of a line, text or outline


of an element:
<svg height="80" width="300">
<g fill="none" stroke="black">
<path stroke-width="2" d="M5 20 l215 0" />
<path stroke-width="4" d="M5 40 l215 0" />
<path stroke-width="6" d="M5 60 l215 0" />
</g>
</svg>

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 128
SVG stroke-linecap Property

• The stroke-linecap property defines different types of endings to an


open path:
<svg height="80" width="300">
<g fill="none" stroke="black" stroke-width="6">
<path stroke-linecap="butt" d="M5 20 l215 0" />
<path stroke-linecap="round" d="M5 40 l215 0" />
<path stroke-linecap="square" d="M5 60 l215 0" />
</g>
</svg>

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 129
SVG stroke-dasharray Property

• The stroke-dasharray property is used to create dashed lines:


<svg height="80" width="300">
<g fill="none" stroke="black" stroke-width="4">
<path stroke-dasharray="5,5" d="M5 20 l215 0" />
<path stroke-dasharray="10,10" d="M5 40 l215 0" />
<path stroke-dasharray="20,10,5,5,5,10" d="M5 60 l215 0" />
</g>
</svg>

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 130
SVG Filters
• SVG Filters are used to add special effects to SVG graphics.
• The available filter elements in SVG are:
– <feBlend> - filter for combining images
– <feColorMatrix> - filter for color transforms
– <feComponentTransfer>
– <feComposite>
– <feConvolveMatrix>
– <feDiffuseLighting>
– <feDisplacementMap>
– <feFlood>
– <feGaussianBlur>
– <feImage>
– <feMerge>
– <feMorphology>
– <feOffset> - filter for drop shadows
– <feSpecularLighting>
– <feTile>
– <feTurbulence>
– <feDistantLight> - filter for lighting
– <fePointLight> - filter for lighting
– <feSpotLight> - filter for lighting
• We can use multiple filters on each SVG element!
• Internet Explorer 9 and earlier versions do not support SVG filters.
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 131
<defs> and <filter>

• All internet SVG filters are defined within a <defs> element. The
<defs> element is short for definitions and contains definition of special
elements (such as filters).
• The <filter> element is used to define an SVG filter. The <filter>
element has a required id attribute which identifies the filter. The
graphic then points to the filter to use.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 132


SVG <feGaussianBlur>

• The <feGaussianBlur> element is used to create blur effects:


<svg height="110" width="110">
<defs>
<filter id="f1" x="0" y="0">
<feGaussianBlur in="SourceGraphic" stdDeviation="15" />
</filter>
</defs>
<rect width="90" height="90" stroke="green" stroke-width="3"
fill="yellow" filter="url(#f1)" />
</svg>
• The id attribute of the <filter> element defines a unique name for the filter
• The blur effect is defined with the <feGaussianBlur> element
• The in="SourceGraphic" part defines that the effect is created for the entire
element
• The stdDeviation attribute defines the amount of the blur
• The filter attribute of the <rect> element links the element to the "f1" filter

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 133
SVG Drop Shadows

• SVG <feOffset>
• The <feOffset> element is used to create drop shadow effects. The idea is to
take an SVG graphic (image or element) and move it a little bit in the xy
plane.
• The first example offsets a rectangle (with <feOffset>), then blend the
original on top of the offset image (with <feBlend>):
<svg height="120" width="120">
<defs>
<filter id="f1" x="0" y="0" width="200%" height="200%">
<feOffset result="offOut" in="SourceGraphic" dx="20" dy="20" />
<feBlend in="SourceGraphic" in2="offOut" mode="normal" />
</filter>
</defs>
<rect width="90" height="90" stroke="green" stroke-width="3"
fill="yellow" filter="url(#f1)" />
</svg>
• The id attribute of the <filter> element defines a unique name for the filter
• The filter attribute of the <rect> element links the element to the "f1" filter

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 134
Other Example

• the offset image can be blurred (with <feGaussianBlur>):


• <svg height="140" width="140">
<defs>
<filter id="f2" x="0" y="0" width="200%" height="200%">
<feOffset result="offOut" in="SourceGraphic" dx="20" dy="20" />
<feGaussianBlur result="blurOut" in="offOut"
stdDeviation="10" />
<feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
</filter>
</defs>
<rect width="90" height="90" stroke="green" stroke-width="3"
fill="yellow" filter="url(#f2)" />
</svg>
• The stdDeviation attribute of the <feGaussianBlur> element defines the
amount of the blur

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 135
Other Example

• make the shadow black:


• <svg height="140" width="140">
<defs>
<filter id="f3" x="0" y="0" width="200%" height="200%">
<feOffset result="offOut" in="SourceAlpha" dx="20" dy="20" />
<feGaussianBlur result="blurOut" in="offOut"
stdDeviation="10" />
<feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
</filter>
</defs>
<rect width="90" height="90" stroke="green" stroke-width="3"
fill="yellow" filter="url(#f3)" />
</svg>
• The in attribute of the <feOffset> element is changed to "SourceAlpha"
which uses the Alpha channel for the blur instead of the entire RGBA
pixel
EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 136
Other Example

• treat the shadow as a color:


• <svg height="140" width="140">
<defs>
<filter id="f4" x="0" y="0" width="200%" height="200%">
<feOffset result="offOut" in="SourceGraphic" dx="20" dy="20" />
<feColorMatrix result="matrixOut" in="offOut" type="matrix"
values="0.2 0 0 0 0 0 0.2 0 0 0 0 0 0.2 0 0 0 0 0 1 0" />
<feGaussianBlur result="blurOut" in="matrixOut" stdDeviation="10" />
<feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
</filter>
</defs>
<rect width="90" height="90" stroke="green" stroke-width="3"
fill="yellow" filter="url(#f4)" />
</svg>
• The <feColorMatrix> filter is used to transform the colors in the offset
image closer to black. The three values of '0.2' in the matrix all get
multiplied by the red, green and blue channels. Reducing their values brings
the colors closer to black (black is 0)

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 137
SVG Gradients

• A gradient is a smooth transition from one color to another. In addition,


several color transitions can be applied to the same element.
• There are two main types of gradients in SVG:
– Linear
– Radial
SVG Linear Gradient - <linearGradient>
• The <linearGradient> element is used to define a linear gradient.
• The <linearGradient> element must be nested within a <defs> tag. The
<defs> tag is short for definitions and contains definition of special
elements (such as gradients).
• Linear gradients can be defined as horizontal, vertical or angular gradients:
• Horizontal gradients are created when y1 and y2 are equal and x1 and x2
differ
• Vertical gradients are created when x1 and x2 are equal and y1 and y2 differ
• Angular gradients are created when x1 and x2 differ and y1 and y2 differ

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 138


Example

• Define an ellipse with a horizontal linear gradient from yellow to red:


• <svg height="150" width="400">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
</linearGradient>
</defs>
<ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad1)" />
</svg>

• The id attribute of the <linearGradient> tag defines a unique name for


the gradient
• The x1, x2, y1,y2 attributes of the <linearGradient> tag define the start
and end position of the gradient
• The color range for a gradient can be composed of two or more colors.
Each color is specified with a <stop> tag. The offset attribute is used to
define where the gradient color begin and end
• The fill attribute links the ellipse element to the gradient
EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 139
Example

• Define an ellipse with a vertical linear gradient from yellow to red:


• <svg height="150" width="400">
<defs>
<linearGradient id="grad2" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
</linearGradient>
</defs>
<ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad2)" />
</svg>

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 140
Example

• Define an ellipse with a horizontal linear gradient from yellow to red,


and add a text inside the ellipse:
• <svg height="150" width="400">
<defs>
<linearGradient id="grad3" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
</linearGradient>
</defs>
<ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad3)" />
<text fill="#ffffff" font-size="45" font-family="Verdana" x="150" y="86">
SVG</text>
</svg>
• The <text> element is used to add a text

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 141
SVG Radial Gradient - <radialGradient>

• The <radialGradient> element is used to define a radial gradient.


• The <radialGradient> element must be nested within a <defs> tag. The
<defs> tag is short for definitions and contains definition of special
elements (such as gradients).

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 142


Example
• <svg height="150" width="500">
<defs>
<radialGradient id="grad1" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
<stop offset="0%" style="stop-color:rgb(255,255,255);
stop-opacity:0" />
<stop offset="100%" style="stop-color:rgb(0,0,255);stop-opacity:1" />
</radialGradient>
</defs>
<ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad1)" />
</svg>
• The id attribute of the <radialGradient> tag defines a unique name for
the gradient
• The cx, cy and r attributes define the outermost circle and the fx and fy
define the innermost circle
• The color range for a gradient can be composed of two or more colors.
Each color is specified with a <stop> tag. The offset attribute is used to
define where the gradient color begin and end
• The fill attribute links the ellipse element to the gradient

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 143
Example

• Define another ellipse with a radial gradient from white to blue:


• <svg height="150" width="500">
<defs>
<radialGradient id="grad2" cx="20%" cy="30%" r="30%" fx="50%" fy="50%">
<stop offset="0%" style="stop-color:rgb(255,255,255);
stop-opacity:0" />
<stop offset="100%" style="stop-color:rgb(0,0,255);stop-opacity:1" />
</radialGradient>
</defs>
<ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad2)" />
</svg>

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 144
SVG Examples (Basic Shapes)
1. A circle
2. A rectangle
3. A rectangle with opacity
4. A rectangle with opacity 2
5. A rectangle with rounded corners
6. An ellipse
7. Three ellipses on top of each other
8. Two ellipses
9. A line
10. A polygon with three sides
11. A polygon with four sides
12. A star
13. Another star
14. A polyline
15. Another polyline
16. A path
17. A quadratic Bézier curve
18. Write a text
19. Rotate a text
20. Text on several lines
21. Text as a link
22. Defines the color of a line, text or outline (stroke)
23. Defines the width of a line, text or outline (stroke-width)
24. Defines different types of endings to an open path (stroke-linecap)
25. Defines dashed lines (stroke-dasharray)

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 145


HTML5 Video

• Before HTML5, there was no standard for showing videos on a web


page.
• Before HTML5, videos could only be played with a plug-in (like flash).
• The HTML5 <video> element specifies a standard way to embed a
video in a web page.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 146


The HTML <video> Element

• The <video> tag specifies video, such as a movie clip or other video
streams.
• Currently, there are 3 supported video formats for the <video> element:
MP4, WebM, and Ogg:
• MP4 = MPEG 4 files with H264 video codec and AAC audio codec
• WebM = WebM files with VP8 video codec and Vorbis audio codec
• Ogg = Ogg files with Theora video codec and Vorbis audio codec
• MIME Types for Video Formats
Format MIME-type
MP4 video/mp4
WebM video/webm
Ogg video/ogg

• Any text between the <video> and </video> tags will be displayed in browsers that do not
support the <video> element.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 147


Example

• <video width="320" height="240" >


<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
• The <source> tag is used to specify multiple media resources for media elements, such as <video> and
<audio>.
• The <source> tag allows you to specify alternative video/audio files which the browser may choose
from, based on its media type or codec support.

Attribute Value Description


media media_query Specifies the type of media
resource
src URL Specifies the URL of the
media file
type media_type Specifies the media type of the
media resource

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 148
Optional Attributes for <video>

Attribute Value Description

autoplay autoplay Specifies that the video will start playing as soon as it is
ready
controls controls Specifies that video controls should be displayed (such
as a play/pause button etc).
height pixels Sets the height of the video player
loop loop Specifies that the video will start over again, every time
it is finished
muted muted Specifies that the audio output of the video should be
muted
poster URL Specifies an image to be shown while the video is
downloading, or until the user hits the play button
preload auto Specifies if and how the author thinks the video should
metadata be loaded when the page loads
none
src URL Specifies the URL of the video file
width pixels Sets the width of the video player

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 149


Contd..

autoplay • <video controls autoplay> </video>


controls • <video controls> </video>
height / width • <video width="320" height="240" controls> </video>
loop • <video controls loop> </video>
muted • <video controls muted> </video>
poster • <video controls poster="multimedia/logo.jpg"> </video>

preload • <video controls preload="none"> </video>


src • <video src="movie.ogg" controls> </video>

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 150


HTML5 Audio

• The HTML5 <audio> element specifies a standard way to embed audio


in a web page.
• Before HTML5, audio files could only be played with a plug-in (like
flash).
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
• The controls attribute adds audio controls, like play, pause, and volume.
• Text between the <audio> and </audio> tags will display in browsers
that do not support the <audio> element.
• Multiple <source> elements can link to different audio files. The
browser will use the first recognized format.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 151


HTML Audio - Media Types

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 152


HTML5 Audio Tags

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 153


Attributes of HTML <audio> Tag

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 154


Attributes of HTML <audio> Tag

<audio controls autoplay> </audio>


autoplay

controls <audio controls></audio>


loop <audio controls loop></audio>
muted <audio controls muted></audio>
preload <audio controls preload="none“></audio>
<audio src="koel.mp3" controls>
src Your browser does not support the audio element.
</audio>

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 155


HTML APIs

• HTML Geolocation
• HTML Drag/Drop
• HTML Local Storage
• HTML App Cache
• HTML Web Workers
• HTML SSE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 156


HTML API :: HTML Geolocation

• The HTML Geolocation API is used to get the geographical position of


a user.
• Since this can compromise user privacy, the position is not available
unless the user approves it.
• Note: Geolocation is much more accurate for devices with GPS

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 157
Using HTML Geolocation
• Use the getCurrentPosition() method to get the user's position.
• The example below is a simple Geolocation example returning the latitude and
longitude of the user's position:
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
• If Geolocation is supported, run the getCurrentPosition() method. If not, display a
message to the user
• If the getCurrentPosition() method is successful, it returns a coordinates object to the
function specified in the parameter ( showPosition )
• The showPosition() function gets the displays the Latitude and Longitude

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 158
Handling Errors and Rejections
• getCurrentPosition() method is used to handle errors. It specifies a function to run if
it fails to get the user's location:
• function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
• Permission denied - The user did not allow Geolocation
• Position unavailable - It is not possible to get the current location
• Timeout - The operation timed out

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 159
Displaying the Result in a Map

• To display the result in a map, you need access to a map service that can
use latitude and longitude, like Google Maps
• function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;

var img_url = "http://maps.googleapis.com/maps/api/staticmap?


center=
"+latlon+"&zoom=14&size=400x300&sensor=false";

document.getElementById("mapholder").innerHTML = "<img
src='"+img_url+"'>";
}
• In the example above we use the returned latitude and longitude data to
show the location in a Google map (using a static image).

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 160
The getCurrentPosition() Method - Return Data

• The getCurrentPosition() method returns an object if it is successful.


The latitude, longitude and accuracy properties are always returned. The
other properties below are returned if available.
Property Description
coords.latitude The latitude as a decimal number

coords.longitude The longitude as a decimal number


coords.accuracy The accuracy of position

coords.altitude The altitude in meters above the mean sea level

coords.altitudeAccuracy The altitude accuracy of position

coords.heading The heading as degrees clockwise from North

coords.speed The speed in meters per second


timestamp The date/time of the response
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 161
watchPosition() method

• watchPosition() - Returns the current position of the user and continues


to return updated position as the user moves (like the GPS in a car).
• clearWatch() - Stops the watchPosition() method.
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 162
HTML5 Drag and Drop

• Drag and drop is a very common feature. It is when you "grab" an


object and drag it to a different location.
• In HTML5, drag and drop is part of the standard, and any element can
be draggable.

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 163
• Make an Element Draggable
• First of all: To make an element draggable, set the draggable attribute to
true:
<img draggable="true">
• What to Drag - ondragstart and setData()
• Then, specify what should happen when the element is dragged.
• In the example , the ondragstart attribute calls a function, drag(event),
that specifies what data to be dragged.
• The dataTransfer.setData() method sets the data type and the value of
the dragged data:
• function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
• In this case, the data type is "text" and the value is the id of the
draggable element ("drag1").

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 164


• Where to Drop - ondragover
• The ondragover event specifies where the dragged data can be dropped.
• By default, data/elements cannot be dropped in other elements. To allow
a drop, we must prevent the default handling of the element.
• This is done by calling the event.preventDefault() method for the
ondragover event:
• event.preventDefault()

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 165


• Do the Drop - ondrop
• When the dragged data is dropped, a drop event occurs.
• In the example above, the ondrop attribute calls a function, drop(event):
• function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
• Call preventDefault() to prevent the browser default handling of the
data (default is open as link on drop)
• Get the dragged data with the dataTransfer.getData() method. This
method will return any data that was set to the same type in the
setData() method
• The dragged data is the id of the dragged element ("drag1")
• Append the dragged element into the drop element

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 166


HTML5 Local Storage


• With local storage, web applications can store data locally within the
user's browser.
• Before HTML5, application data had to be stored in cookies, included
in every server request. Local storage is more secure, and large amounts
of data can be stored locally, without affecting website performance.
• Unlike cookies(4KB per cookie), the storage limit is far larger (at least
5MB) and information is never transferred to the server.
• Local storage is per domain. All pages, from one domain, can store and
access the same data.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 167


HTML Local Storage Objects

• HTML local storage provides two objects for storing data on the client:
• window.localStorage - stores data with no expiration date
• window.sessionStorage - stores data for one session (data is lost when
the tab is closed)
• Before using local storage, check browser support for localStorage and
sessionStorage:
• if(typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 168


The localStorage Object

• The localStorage object stores the data with no expiration date. The data
will not be deleted when the browser is closed, and will be available the
next day, week, or year.
• Example
• // Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML =
localStorage.getItem("lastname");

• The syntax for removing the "lastname" localStorage item is as follows:


• localStorage.removeItem("lastname");

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 169
The sessionStorage Object

• The sessionStorage object is equal to the localStorage object, except


that it stores the data for only one session. The data is deleted when the
user closes the browser window.

EXAMPLE
Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 170
HTML5 Application Cache

• HTML5 introduces application cache, which means that a web


application is cached, and accessible without an internet connection.
• Application cache gives an application three advantages:
• Offline browsing - users can use the application when they're offline
• Speed - cached resources load faster
• Reduced server load - the browser will only download updated/changed
resources from the server

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 171


• HTML Cache Manifest Example
• The example below shows an HTML document with a cache manifest
(for offline browsing):
• Example
• <!DOCTYPE HTML>
<html manifest="demo.appcache">

<body>
The content of the document......
</body>

</html>

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 172


• Cache Manifest Basics
• To enable application cache, include the manifest attribute in the
document's <html> tag:
• <!DOCTYPE HTML>
<html manifest="demo.appcache">
...
</html>
• Every page with the manifest attribute specified will be cached when
the user visits it. If the manifest attribute is not specified, the page will
not be cached (unless the page is specified directly in the manifest file).
• The recommended file extension for manifest files is: ".appcache"
• A manifest file needs to be served with the correct media type, which
is "text/cache-manifest". Must be configured on the web server.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 173


The Manifest File

• The manifest file is a simple text file, which tells the browser what to
cache (and what to never cache).
• The manifest file has three sections:
• CACHE MANIFEST - Files listed under this header will be cached
after they are downloaded for the first time
• NETWORK - Files listed under this header require a connection to the
server, and will never be cached
• FALLBACK - Files listed under this header specifies fallback pages if
a page is inaccessible

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 174


• CACHE MANIFEST
• The first line, CACHE MANIFEST, is required:
• CACHE MANIFEST
/theme.css
/logo.gif
/main.js
• The manifest file above lists three resources: a CSS file, a GIF image,
and a JavaScript file. When the manifest file is loaded, the browser will
download the three files from the root directory of the web site. Then,
whenever the user is not connected to the internet, the resources will
still be available.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 175


• NETWORK
• The NETWORK section below specifies that the file "login.asp" should
never be cached, and will not be available offline:
• NETWORK:
login.asp
• An asterisk can be used to indicate that all other resources/files require
an internet connection:
• NETWORK:
*

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 176


• FALLBACK
• The FALLBACK section below specifies that "offline.html" will be
served in place of all files in the /html/ catalog, in case an internet
connection cannot be established:
• FALLBACK:
/html/ /offline.html
• Note: The first URI is the resource, the second is the fallback.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 177


• Updating the Cache
• Once an application is cached, it remains cached until one of the following
happens:
• The user clears the browser's cache
• The manifest file is modified (see tip below)
• The application cache is programmatically updated
• Example - Complete Cache Manifest File
• CACHE MANIFEST
# 2012-02-21 v1.0.0
/theme.css
/logo.gif
/main.js
NETWORK:
login.asp
FALLBACK:
/html/ /offline.html

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 178


• Lines starting with a "#" are comment lines, but can also serve another
purpose. An application's cache is only updated when its manifest file
changes. If you edit an image or change a JavaScript function, those
changes will not be re-cached. Updating the date and version in a
comment line is one way to make the browser re-cache your files. Notes
on Application Cache
• Be careful with what you cache.
• Once a file is cached, the browser will continue to show the cached
version, even if you change the file on the server. To ensure the browser
updates the cache, you need to change the manifest file.
• Note: Browsers may have different size limits for cached data (some
browsers have a 5MB limit per site).

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 179


HTML5 Web Workers

• A web worker is a JavaScript running in the background, without


affecting the performance of the page.
• What is a Web Worker?
• When executing scripts in an HTML page, the page becomes
unresponsive until the script is finished.
• A web worker is a JavaScript that runs in the background,
independently of other scripts, without affecting the performance of the
page. You can continue to do whatever you want: clicking, selecting
things, etc., while the web worker runs in the background.

EXAMPLE

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 180


• Check Web Worker Support
• Before creating a web worker, check whether the user's browser
supports it:
• if(typeof(Worker) !== "undefined") {
// Yes! Web worker support!
// Some code.....
} else {
// Sorry! No Web Worker support..
}

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 181


• Create a Web Worker File
• Now, let's create our web worker in an external JavaScript.
• Here, we create a script that counts. The script is stored in the
"demo_workers.js" file:
• var i = 0;

function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()",500);
}

timedCount();
• The important part of the code above is the postMessage() method - which
is used to post a message back to the HTML page.
• Note: Normally web workers are not used for such simple scripts, but for
more CPU intensive tasks.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 182


• Create a Web Worker Object
• Now that we have the web worker file, we need to call it from an
HTML page.
• The following lines checks if the worker already exists, if not - it creates
a new web worker object and runs the code in "demo_workers.js":
• if(typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
• Then we can send and receive messages from the web worker.
• Add an "onmessage" event listener to the web worker.
• w.onmessage = function(event){
document.getElementById("result").innerHTML = event.data;
};
• When the web worker posts a message, the code within the event
listener is executed. The data from the web worker is stored in
event.data.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 183


• Terminate a Web Worker
• When a web worker object is created, it will continue to listen for
messages (even after the external script is finished) until it is
terminated.
• To terminate a web worker, and free browser/computer resources, use
the terminate() method:
• w.terminate();
• Reuse the Web Worker
• If you set the worker variable to undefined, after it has been terminated,
you can reuse the code:
• w = undefined;

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 184


• Web Workers and the DOM
• Since web workers are in external files, they do not have access to the
following JavaScript objects:
• The window object
• The document object
• The parent object

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 185


HTML5 Server-Sent Events

• Server-Sent Events - One Way Messaging


• A server-sent event is when a web page automatically gets updates from
a server.
• This was also possible before, but the web page would have to ask if
any updates were available. With server-sent events, the updates come
automatically.
• Examples: Facebook/Twitter updates, stock price updates, news feeds,
sport results, etc.

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 186


• Receive Server-Sent Event Notifications
• The EventSource object is used to receive server-sent event notifications:
• Example
• var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};

• Example explained:
• Create a new EventSource object, and specify the URL of the page sending
the updates (in this example "demo_sse.php")
• Each time an update is received, the onmessage event occurs
• When an onmessage event occurs, put the received data into the element
with id="result"

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 187


• Check Server-Sent Events Support
• In the tryit example above there were some extra lines of code to check
browser support for server-sent events:
• if(typeof(EventSource) !== "undefined") {
// Yes! Server-sent events support!
// Some code.....
} else {
// Sorry! No server-sent events support..
}

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 188


• Server-Side Code Example
• For the example above to work, you need a server capable of sending
data updates (like PHP or ASP).
• The server-side event stream syntax is simple. Set the "Content-Type"
header to "text/event-stream". Now you can start sending event streams.
• Code in PHP (demo_sse.php):
• <?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 189


• Code in ASP (VB) (demo_sse.asp):
• <%
Response.ContentType = "text/event-stream"
Response.Expires = -1
Response.Write("data: The server time is: " & now())
Response.Flush()
%>
• Code explained:
• Set the "Content-Type" header to "text/event-stream"
• Specify that the page should not cache
• Output the data to send (Always start with "data: ")
• Flush the output data back to the web page

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 190


The EventSource Object

Events Description
When a connection to the
onopen
server is opened
onmessage When a message is received
onerror When an error occurs

Web Technology / Mirzanur Rahman / Dept of IT / GU /2015 191


Thank You

You might also like