Computer Animation & Multimedia
Introduction to HTML/XHTML : Origins and Evolution of HTML and XHTML, Basic
Syntax of HTML, Standard HTML Document Structure, Basic Text Markup, Images,
Hypertext Links, Lists, Tables, Forms,HTML5, Syntactic Differences between HTML and
XHTML.
Origins and Evolution of HTML and XHTML
HTML stands for Hyper Text Markup Language. Hyper Text is text which contains
links to other texts .It is amarkup language consists of a set of markup tags. HTML uses
markup tags to describe web pages. HTML markup tags are usually called HTML tags.
HTML tags are keywords surrounded by angle brackets like <html>. HTML tags come in
pairs like <b> and </b>. The first tag in a pair is the start tag, the second tag isthe end tag.
Start and end tags are also called opening tags and closing tags.
XHTML stands for EXtensible HyperText Markup Language.XHTML is almost identical to
HTML4.01.XHTML is a stricter and cleaner version of HTML 4.01.
Versions of HTML and XHTML
Original intent of HTML: General layout of documents that could be displayed by a
wide variety ofcomputers.
HTML 1.0
• HTML 1.0 was the first release of HTML to the world
• The language was very limiting.
HTML 2.0
• HTML 2.0 included everything from the original 1.0 specifications
• HTML 2.0 was the standard for website design until January 1997
• Defined many core HTML features for the first time.
HTML 3.2 - 1997
• The browser-specific tags kept coming.
• First version developed and standardized exclusively by the W3C.
HTML 4.0 – 1997
• Introduced many new features and deprecated many older features.
• Support for HTML’s new supporting presentational language, CSS.
HTML 4.01 - 1999
• A cleanup of 4.0,
• it faces 2 problems
- it specifies loose syntax rules
its specification does not define how a user agent (browser) is to recover when
erroneous code isencountered
XHTML 1.0 – 2000
• Redefinition of HTML4.01 using XML, instead of SGML& HTML with stronger
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 1 of 32
Computer Animation & Multimedia
syntactic rules
• XHTML 1.0 is three standards: Strict, Transitional and Frameset.
- Strict standard requires all of the syntax rules of XHTML1.0 to be followed
- Transitional standard allows deprecated features of XHTML1.0 to be
included.
- Frameset standard allows the collection of frame elements and attributes to
be includedalthough they have been deprecated.
XHTML 1.1 – 2001
• Modularization of XHTML 1.0 , drops some of the features of its predecessor such
as frames.
HTML 5 – January 2008
• Latest specification of the HTML.
• HTML5 was published as a Working Draft by the W3C.
Difference between HTML and HTML5
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 2 of 32
Computer Animation & Multimedia
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 3 of 32
Computer Animation & Multimedia
Basic Syntax of HTML
Fundamental synctactic units of HTML are called tags.Elements are defined by tags.Tag
format:
• Opening tag: <name>
• Closing tag: </name>
Most tags appear in pairs.The opening tag and its closing tag together specify a container
for the content theyenclose. Not all tags have content.If a tag has no content, its form is
<name /> .The container and its content together are called an element.
If a tag has attributes, they appear between its name and the right bracket of the opening
tag.
<a href="default.html"> this is a link </a>
Comment form: <!-- … -->.Comments increases the readability of programs.Browsers
ignore comments, unrecognizable tags, line breaks, multiple spaces, and tabs.Tags are
suggestions to the browser.
Standard HTML Document Structure
• The first line of every HTML document is a DOCTYPE command.
<!DOCTYPE html>
An HTML document must include the four tags <html>, <head>, <title>, and <body>. The
<html> tag identifies the root element of the document. HTML documents always have an
<html> tag immediatelyfollowing the DOCTYPE command, and they always end with the
closing html tag, </html>.
The html element includes an attribute lang. Which specifies the language in which the
document is written.
<html lang = “en”>
en means english . An html document consists of 2 parts: head and body.
The head element provides information about the document. The head element always
contains 2 simple elements, a title element and meta element. The meta element is used to
provide additional information about a document. The meta element has no content, all
information is specified with attributes. The meta tag specifies the character set used to write
the document.
<meta charset = “utf-8” />
The slash at the end of the tag specifies it has no closing tag, It has a combined opening and
closing tag . Thecontent of the title element is displayed by the browser in the browser
window’s title bar. The body of a document provides content of the document .
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 4 of 32
Computer Animation & Multimedia
<!DOCTYPE html>
<!- - File name and document purpose - ->
<html lang = “en”>
<head>
<title> A title for the document </title>
<meta charset = “utf-8” / >
</head>
<body>
……
</body>
</html>
Basic Text Markup
Describes how the text content of an XHTML document can be formatted with XHTML
tags.
1. Paragraphs
2. Line Breaks
3. Preserving white space
4. Headings
5. Block Quotes
6. Font styles & size
7. Character Entities
8. Horizontal Rules
9. Meta Element
1. Paragraph Element
Text is normally placed in paragraph elements . The <p> tag breaks the current line
and inserts ablank line ( the new line gets the beginning of the content of the
paragraph). The closing tag is required in XHTML, not in HTML. Also multiple spaces in
the text are replaced by single space.
<p>Mary had a little lamb, its fleece was white as snow.</p>
OUTPUT
Mary had a little lamb, its fleece was white as snow.
<!DOCTYPE html>
<!-- greet.hmtl
A trivial document
-->
<html lang = “en″>
<head> <title> Our first document </title>
<meta charset= “utf-8” />
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 5 of 32
Computer Animation & Multimedia
</head>
<body>
<p>
Greetings from your Webmaster!
</p>
</body>
</html>
2. Line breaks
The effect of the <br /> tag is the same as that of <p>, except for the blank line. It can
have no contenttherefore no closing tag!
<p> Mary had a little lamb, <br> its fleece was white as snow.</p>
Typical display of this text:
Mary had a little lamb, its fleece was white as snow.
3. Preserving whitespaces
It is used to preserve white spaces in text. Text in a <pre> element preserves both
spaces and line breaks.
</pre> .It blocks the browser from eliminating multiple spaces
Mary
had a
little
lamb
</pre></p>
Display(output)
Mary
had a
little
lamb
4. Headings
Six sizes, 1 - 6,are used for specifying heading. It is specified with <h1> to <h6>.1, 2,
and 3 use font sizesthat are larger than the default font size. 4 uses the default size.5 and 6
use smaller font sizes.
< !DOCTYPE html >
<!-- headings.html
An example to illustrate headings -->
<html lang = “en″>
<head> <title> Headings </title>
<meta charset = “utf-8” />
</head>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 6 of 32
Computer Animation & Multimedia
<body>
<h1> Aidan’s Airplanes (h1) </h1>
<h2> The best in used airplanes (h2) </h2>
<h3> "We’ve got them by the hangarful" (h3)
</h3>
<h4> We’re the guys to see for a good usedairplane (h4) </h4>
<h5> We offer great prices on great planes
(h5) </h5>
<h6> No returns, no guarantees, no refunds,all sales are final! (h6) </h6>
</body>
</html>
5. Blockquotes
The Content of <blockquote> can be made to look different from the surrounding
text .It set a block of textoff from the normal flow and appearance of text. Browsers often
indent, and sometimes italicize.
<!DOCTYPE html>
<!-- blockquote.html
An example to illustrate a blockquote -->
<html lang = “en">
<head><title> Blockquotes </title>
<meta charset= “utf-8”/>
</head>
<body>
<p>
Abraham Lincoln is generally regarded as one of the greatest presidentsof the U.S. His
most famous speech was delivered in Gettysburg, Pennsylvania, during the Civil War.
This speech began with </p>
<blockquote><p>
"Fourscore and seven years ago our fathers brought forth on this continent, a new
nation, conceived in Liberty, and dedicated to theproposition that all men are created
equal.”
</p>
</blockquote>
<p>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 7 of 32
Computer Animation & Multimedia
Whatever one's opinion of Lincoln, no one can deny the enormous andlasting effect he
had on the U.S. </p>
</body></html>
OUTPUT
Abraham Lincoln is generally regarded as one of the greatest presidents of the U.S. His most
famous speech was delivered in Gettysburg, Pennsylvania, during the Civil War. This
speech began with
"Fourscore and seven years ago our fathers brought forth on this continent, a new nation,
conceived in Liberty, and dedicated to the proposition that all men are created equal.”
Whatever one's opinion of Lincoln, no one can deny the enormous and lasting effect he had
on the U.S.
6. Font Styles and Sizes (can be nested)
– Boldface - <b>
– Italics - <i>
– Larger - <big>
– Smaller - <small>
The <big> sleet <big> in <big> <i> Crete
</i><br /> lies </big> completely </big>in </big> the street
OUTPUT
The sleet in Crete
lies completely in the street
These tags are not affected if they appear in the content of a <blockquote>, unless there is a
conflict (e.g.,italics)
– Superscripts and subscripts
• Subscripts with <sub>
• Superscripts with <sup> Example: x<sub>2</sub><sup>3</sup>
Display: x23
There are few tags for fonts that are still in widespread use, called content based style
tags.They are calledcontent based because the tag indicates the particular kind of text that
appear in their content.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 8 of 32
Computer Animation & Multimedia
• The emphasis tag- <em>=Most browsers use italics for such content
• The strong tag -<strong>= Browsers often set the content of strong elements in bold
• The <code> = used to specify a monospace font usually used for program code
cost = quantity * price
tags are categorized into two
1)Block 2)Inline
• Block tags breaks the current line so that its content appears in a new line
Eg: heading and blockquote tag
• Inline tags does not implicitly include a line break except <br />.The content of the
inline tag appears on the current line
Eg: <em> and <strong>
• Inline versus block elements
• Block elements CANNOT be nested in inline elements.
7. Character Entities
- To include special characters
Char. Entity Meaning
& & Ampersand
< < Less than
> > Greater than
” " Double quote
’ ' Single quote
¼ ¼ One quarter
½ ½ One half
¾ ¾ Three quarters
° Degree
(space) Non-breaking space
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 9 of 32
Computer Animation & Multimedia
8. Horizontal rules
<hr><hr />
Used to separate the parts of a document from each other making the document easier to
read by placing horizontal line between them. This causes a line break and draws a line
across the screen.
9. The meta element
The meta element (for search engines) Used to provide additional information about
a document, withattributes, not content. Two attributes that are used to provide information
are name and content
<meta name=“Title” content=“World wide web”/>
<meta name=“Author” content=“Sebesta”/>
<meta name=“keywords” content=“html,xml,javascript,ajax,xhtml” />
Web search engines use the information provided with the meta element to categorize the
web documents intheir indices .So if the author of a document seeks widespread exposure
for the document ,one or more metaelements are included to ensure that it will be found
by at least some web searches .
Images
HTML img tag is used to display image on the web page. HTML img tag is an empty
tag that contains attributes only, closing tags are not used in HTML image element.
Image Formats:
1. GIF (Graphic Interchange Format)8-bit color (256 different colors)
2. JPEG (Joint Photographic Experts Group)
It has 24-bit color representation (16 million different colors). Both use compression,
but JPEGcompression is better.
3. Portable Network Graphics (PNG)
It is relatively new. Should eventually replace both gif and jpeg
Images are inserted into a document with the <img /> tag with the src attribute. Src means
source of the image. The alt attribute means” Alternate Text” which is required by XHTML
where the image cannot be loaded by the browser. Purpose of alt attribute is for non
graphical browsers and browsers with images turned off.
<img src = “icet.jpg" alt = "Picture of Icet " />
The <img> tag has 30 different attributes, including width and height (in pixels)
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 10 of 32
Computer Animation & Multimedia
<!DOCTYPE html>
<!-- image.html
An example to illustrate an image
-->
<html lang = “en”>
<head> <title> Images </title>
<meta charset=“utf-8”>
</head>
<body>
<h1> Aidan's Airplanes </h1>
<h2> The best in used airplanes </h2>
<h3> "We've got them by the hangarful“</h3>
<h2> Special of the month </h2>
<p> 1960 Cessna 210 <br />
577 hours since major engine overhaul <br /> 1022 hours since prop
overhaul
<br /><br />
<img src = "c210new.jpg" alt = "Picture of a Cessna 210"/>
<br />
Buy this fine airplane today at a remarkably low price <br /> Call 999-555-1111 today!
</p>
</body>
</html>
OUTPUT
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 11 of 32
Computer Animation & Multimedia
Hypertext Link
Link is the convenient way for the browser user to get from one document to any
logically related document. A hypertext link acts as a pointer to some resource. The resource
can be an HTML document anywhere on the web, or it may be another place in the same
document or be a specific place (rather than thetop) in some other document.
A link is specified with the href (hypertext reference) attribute of <a> (the anchor tag).<a>
tag is inline tag.
The content of <a> is the visual link in the document (clickable link). Links are implicitly
rendered in adifferent color than the surrounding text. Sometimes they underlined.
<!DOCTYPE html>
<!-- link.html
An example to illustrate a link-->
<html lang = “en″>
<head>
<title> Links </title>
<meta charset=“UTF-8” />
</head>
<body>
<h1> Aidan's Airplanes </h1>
<h2> The best in used airplanes </h2>
<h3> "We've got them by the hangarful"</h3>
<h2> Special of the month </h2>
<p>
1960 Cessna 210 <br />
<a href = "C210data.html"> Information on the Cessna 210 </a>
</p>
</body>
</html>
If the target is not at the beginning of the document, the target spot must be marked. Target
labels can bedefined in many different tags with the id attribute, as in
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 12 of 32
Computer Animation & Multimedia
<h1 id = "baskets"> Baskets </h1>
The value of the id attribute must be unique within the document. The link to an id must
be preceded by apound sign (#); If the id is in the same document, this target could be
<a href = "#baskets"> What about baskets? </a>
If the target is in a different document, the document reference must be included
<a href = "myAd.html#baskets”> Baskets </a>
Links can have images:
<a href = "c210data.html“>
<img src = "smallplane.jpg" alt = "Small picture of an airplane " />Info on C210 </a>
Lists
HTML Lists are used to specify lists of information. All lists may contain one or more list
elements. There are three different types of HTML lists:
1. Unordered List or Bulleted List (ul)
2. Ordered List or Numbered List (ol)
3. Description List or Definition List (dl)
Unordered lists
• Unordered list is represented using <ul> tag which is block tag.
• Each item in a list is specified with the content of the <li> tag.
• It can include nested lists.
• When displayed each item is implicitly preceded with a bullet.
<!DOCTYPE html>
<!- - unordered.html -->
<html lang=“en”>
<head>
<title> Unordered list </title>
<meta charset = “utf-8” />
</head>
<body>
<h3> Some Common Single-Engine Aircraft </h3>
<ul>
<li> Cessna Skyhawk </li>
<li> Beechcraft Bonanza </li>
<li> Piper Cherokee </li>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 13 of 32
Computer Animation & Multimedia
</ul>
</body>
</html>
Ordered lists
In ordered list defines a list of items in which the order of the items are matters. An
ordered list is also called a number list. The ordering is given by a numbering scheme, using
Arabic numbers, letters, Roman numerals. Or in other words, ordered list tag is used to
create an ordered list. Ordered lists are those in which the order of items is important .Each
item in the display is preceded by asequence value
-The list is the content of the <ol> tag.
-The default sequential values are Arabic numerals beginning with 1.
<h3> Cessna 210 Engine Starting Instructions </h3>
<ol>
<li> Set mixture to rich </li>
<li> Set propeller to high RPM </li>
<li> Set ignition switch to "BOTH" </li>
<li> Set auxiliary fuel pump switch to "LOW PRIME" </li>
<li> When fuel pressure reaches 2 to 2.5 PSI, push starter button
</li>
</ol>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 14 of 32
Computer Animation & Multimedia
Nested lists
A nested list is a list inside another list. You can create a nested unordered list, or a
nested ordered list, or even an ordered list nested inside an unordered one.
• Any type list can be nested inside any type list
• The nested list must be in a list item
Definition lists
It is used for glossaries, etc. It represents set of terms and their definitions. List is the
content of the <dl>tag. Terms being defined are the content of the <dt> tag. The definitions
themselves are the content of the
<dd> tag.
<h3> Single-Engine Cessna Airplanes </h3>
<dl >
<dt> 152 </dt>
<dd> Two-place trainer </dd>
<dt> 172 </dt>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 15 of 32
Computer Animation & Multimedia
<dd> Smaller four-place airplane </dd>
<dt> 182 </dt>
<dd> Larger four-place airplane </dd>
<dt> 210 </dt>
<dd> Six-place airplane - high performance
</dd>
</dl>
Tables
A table is a matrix of cells, each possibly having content. The cells can include
almost any element. Some cells have row or column labels and some have data. The cells
in the top row often contain columns labels, those in the left most column often contains
row labels and most of the rest of the cells contain the data of the table. The content of a cell
can be text, a heading, a horizontal rule, an image or a nested table. A table is specified as
the content of a <table> tag. A border attribute in HTML 4.01 and XHTML 1.0 in the
<table> tag specifies a border between the cells. This attribute is not present in HTML5. The
styles of the border and rules in a table are specified in HTML 5 with stylesheets.
Tables are given titles with the
<caption> tag, which can immediately follow <table> tag
• Each row of a table is specified as the content of a <tr> tag
• The row labels(headings) are specified as the content of a <th> tag
• The contents of a data cell is specified as the content of a <td> tag
<!DOCTYPE html>
<! - - table.html - ->
<html lang = “en”>
<head>
<title> A simple table </title>
<meta charset = “utf-8” />
</head>
<body>
<table>
<caption> Fruit Juice Drinks </caption>
<tr>
<th> </th>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 16 of 32
Computer Animation & Multimedia
<th> Apple </th>
<th> Orange </th>
<th> Banana </th>
</tr>
<tr>
<th> Breakfast </th>
<td> 0 </td>
<td> 1 </td>
<td> 0 </td>
</tr>
<tr>
<tr>
<th> Lunch </th>
<td> 1 </td>
<td> 0 </td>
<td> 0 </td>
</tr>
<th> Dinner </th>
<td> 0 </td>
<td> 0 </td>
<td> 1 </td>
</tr>
</table>
</body>
</html>
rowspan and colspan attribute
The rowspan and colspan are the attributes of <td> tag. These are used to specify the
number of rows or columns a cell should merge. The rowspan attribute is for merging rows
and the colspan attribute is for merging columns of the table in HTML.
• A table can have two levels of column labels
– If so, the colspan attribute must be set in the <th> tag to specify that the label
must span somenumber of columns.
<tr>
<th colspan = "3"> Fruit Juice Drinks </th>
</tr>
<tr>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 17 of 32
Computer Animation & Multimedia
<th> Apple </th>
<th> Orange </th>
<th> Banana </th>
</tr>
OUTPUT
• If the rows have labels and there is a spanning column label, the upper left corner
must be madelarger, using rowspan
<table border = "border">
<tr>
<td rowspan = "2"> </td>
<th colspan = "3"> Fruit Juice Drinks
</th>
</tr>
<tr>
<th> Apple </th>
<th> Orange </th>
<th> Banana </th>
</tr>
…
</table>
Example
<!DOCTYPE html>
<! - - cellspan.html - ->
<html lang = “en”>
<head>
<title> A simple table </title>
<meta charset = “utf-8” />
</head>
<body>
<table>
<caption> Fruit Juice Drinks and Meals </caption>
<tr>
<td rowspan = "2"> </td>
<th colspan = "3"> Fruit Juice Drinks </th>
</tr>
<tr>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 18 of 32
Computer Animation & Multimedia
<th> </th>
<th> Apple </th>
<th> Orange </th>
<th> Banana </th>
</tr>
<tr>
<th> Breakfast </th>
<td> 0 </td>
<td> 1 </td>
<td> 0 </td>
</tr>
<tr>
<th> Lunch </th>
<td> 1 </td>
<td> 0 </td>
<td> 0 </td>
</tr>
<th> Dinner </th>
<td> 0 </td>
<td> 0 </td>
<td> 1 </td>
</tr>
<tr>
</table>
</body>
</html>
Table Sections
Tables naturally occur in two and sometimes three parts: header, body, and footer.
(Not all tables have anatural footer.) These three parts can be respectively denoted in HTML
with the thead, tbody, and tfoot elements.
• The header includes the column labels, regardless of the number of levels in those labels.
• The body includes the data of the table, including the row labels.
• The footer, when it appears, sometimes has the column labels repeated after the body.
• In some tables,the footer contains totals for the columns of data above .
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 19 of 32
Computer Animation & Multimedia
Forms
• A form is the usual way information is gotten from a browser to a server.
• HTML has tags to create a collection of objects that implement this information
gathering
– The objects are called widgets or controls (e.g., radio buttons, checkboxes, text
,password ,reset, submit )
– All control tags are inline tags
– Most controls are used to gather information from the user in the form of either text
or buttonselections
– Every form data requires submit button
• When the Submit button of a form is clicked, the form data is encoded and are sent
to the server forprocessing
1. The form Element
All of the widgets, or components of a form are defined in the content of a <form>
tag. The only required attribute of <form> is action, which specifies the URL of the
application on the web server that is to be calledwhen the Submit button is clicked.
action = http://www.cs.ucp.edu/cgi-bin/survey.pl
If the form has no action, the value of action is the empty string.
The method attribute of <form> specifies one of the two possible techniques of transferring
the form data tothe server, get and post. The method attribute specifies how to send form-
data to the server. Default is get.Inboth techniques the form data is coded into a text string
when the user clicks the Submit button. This text string is often called query string .
2. The< input> tag
Many of the commonly used controls such as text, passwords checkboxes, Reset,
Submit ,radio buttons etc.are created with the <input> tag.
The type attribute of <input> specifies the kind of widget being created such as checkbox,
text, password,radio button etc.
All the previously listed controls except Reset and submit also require a name attribute
which becomes thename of the value of the control within the form data.
The controls for checkboxes and radio buttons require value attributes which initializes the
value of thecontrol.
Textboxes as well as most other control elements should be labeled.
Eg: <label> Phone: <input type = “text” name = “phone” /> </label>
3. Text
Text control is often used to gather information from the user such as the user’s name
or address.Creates a horizontal box for text input. Default size is 20; it can be changed with
the size attribute.If more characters are entered than will fit, the box is scrolled (shifted) left.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 20 of 32
Computer Animation & Multimedia
<input type = "text" name = "Phone" size = “25“ />
If you don’t want to allow the user to type more characters than will fit, set maxlength,
which causes excess input to be ignored
<input type = "text" name = "Phone” size = “25“ maxlength =“25” />
If the contents of the textbox should not be displayed when it is entered by the user, a
passwordcontrol can be used.
<input type= “password” name = “myPassword” size = “10” maxlength = “10”
– />
In this case, regardless of what characters are typed into a password control, only bullets or
asterisks aredisplayed by the browser.
4. Checkboxes
It is used to collect multiple choice input.A checkbox control is a single button that is
either on/off (checked or not) .Every checkbox requires a name attribute and value attribute,
which is the widget’s value in the formdata when the checkbox is ‘checked’. A checkbox
that is not ‘checked’ (off) contribute no value to the form data. To initialize a checkbox to
‘checked’, the checked attribute of checkbox must be set to "checked“.
Check box should appear in the label elements.
<!DOCTYPE html>
<! - -checkbox.html - ->
<html lang = “en”>
<head>
<title> Checkboxes</title>
<meta charset = =“utf-8” />
</head>
<body>
<p>
Grocery Checklist
</p>
<form action = "">
<p>
<label> <input type = "checkbox" name ="groceries"
value = "milk" checked = "checked“ />Milk </label>
<label><input type = "checkbox" name ="groceries"value = "bread“ /> Bread
</label>
<label> <input type = "checkbox" name = "groceries"value= "eggs“ /> Eggs </label>
</p>
</form>
</body>
</html>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 21 of 32
Computer Animation & Multimedia
Cascading Style Sheets
CSS stands for Cascading Style Sheets. It is a style sheet language which is used to
describe the look and formatting of a document written in markup language. It provides
an additional feature to HTML. It is generally used with HTML to change the style of web
pages and user interfaces. It can also be used with any kind of XML documents including
plain XML, SVG and XUL.
CSS is used along with HTML and JavaScript in most websites to create user interfaces for
web applications and user interfaces for many mobile applications.
The presentation specifications of documents can be more precisely and more
consistently described with style sheets.
• The CSS1 specification was developed in 1996
• CSS2 was released in 1998 • CSS3 is on its way
• CSSs provide the means to control and change presentation of HTML documents
• CSS is not technically HTML, but can be embedded in HTML documents
• The most important benefit of style sheets is their capability of imposing consistency on
the style of documents.
Eg: they allow the author to specify that all occurences of a particular tag use the
same presentation style. Style is specified for a tag by the values of its property.
Benefits of CSS:
1) Solves a big problem : Before CSS, tags like font, color, background style, element
alignments, border and size had to be repeated on every web page. This was a very long
process. For example: If you are developing a large website where fonts and color
information are added on every single page, it will be become a long and expensive
process. CSS was created to solve this problem. It was a W3C recommendation.
2) Saves a lot of time : CSS style definitions are saved in external CSS files so it is possible
to change the entire website by changing just one file.
3) Provide more attributes : CSS provides more detailed attributes than plain HTML to
define the look and feel of the website.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 22 of 32
Computer Animation & Multimedia
CSS Syntax
A CSS rule set contains a selector and a declaration block.
Selector: Selector indicates the HTML element you want to style. It could be any tag like
<h1>, <title> etc.
Declaration Block: The declaration block can contain one or more declarations separated
by a semicolon. For the above example, there are two declarations:
1. color: yellow;
2. font-size: 11 px;
Each declaration contains a property name and value, separated by a colon.
Property: A Property is a type of attribute of HTML element. It could be color, border etc.
Value: Values are assigned to CSS properties. In the above example, value "yellow" is
assigned to color property.
Selector{Property1: value1; Property2: value2; ..........;}
CSS Selector
CSS selectors are used to select the content you want to style. Selectors are the part of
CSS rule set. CSS selectors select HTML elements according to its id, class, type, attribute
etc.
There are several different types of selectors in CSS.
1. CSS Element Selector
2. CSS Id Selector
3. CSS Class Selector
4. CSS Universal Selector
5. CSS Group Selector
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 23 of 32
Computer Animation & Multimedia
1) CSS Element Selector
The element selector selects the HTML element by name.
<!DOCTYPE html>
<html>
<head>
<style>
p{
text-align: center;
color: blue;
}
</style>
</head>
<body>
<p>This style will be applied on every paragraph.</p>
<p id="para1">Me too!</p>
<p>And me!</p>
</body>
</html>
Output:
This style will be applied on every paragraph.
Me too!
And me!
2) CSS Id Selector
The id selector selects the id attribute of an HTML element to select a specific element. An
id is always unique within the page so it is chosen to select a single, unique element.
It is written with the hash character (#), followed by the id of the element.
<!DOCTYPE html>
<html>
<head>
<style>
#para1 {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<p id="para1">Hello Javatpoint.com</p>
<p>This paragraph will not be affected.</p>
</body>
</html>
Output:
Hello Javatpoint.com
This paragraph will not be affected.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 24 of 32
Computer Animation & Multimedia
3) CSS Class Selector
The class selector selects HTML elements with a specific class attribute. It is used with a
period character . (full stop symbol) followed by the class name.
Note: A class name should not be started with a number.
<!DOCTYPE html>
<html>
<head>
<style>
.center {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1 class="center">This heading is blue and center-aligned.</h1>
<p class="center">This paragraph is blue and center-aligned.</p>
</body>
</html>
Output:
This heading is blue and center-aligned.
This paragraph is blue and center-aligned.
CSS Class Selector for specific element
If you want to specify that only one specific HTML element should be affected then you
should use the element name with class selector.
<!DOCTYPE html>
<html>
<head>
<style>
p.center {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1 class="center">This heading is not affected</h1>
<p class="center">This paragraph is blue and center-aligned.</p>
</body>
</html>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 25 of 32
Computer Animation & Multimedia
Output:
This heading is not affected
This paragraph is blue and center-aligned.
4) CSS Universal Selector
The universal selector is used as a wildcard character. It selects all the elements on the pages.
<!DOCTYPE html>
<html>
<head>
<style>
*{
color: green;
font-size: 20px;
}
</style>
</head>
<body>
<h2>This is heading</h2>
<p>This style will be applied on every paragraph.</p>
<p id="para1">Me too!</p>
<p>And me!</p>
</body>
</html>
Output:
This is heading
This style will be applied on every paragraph.
Me too!
And me!
5) CSS Group Selector
The grouping selector is used to select all the elements with the same style definitions.
Grouping selector is used to minimize the code. Commas are used to separate each selector
in grouping.
h1 {
text-align: center;
color: blue;
}
h2 {
text-align: center;
color: blue;
}
p{
text-align: center;
color: blue;
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 26 of 32
Computer Animation & Multimedia
}
As you can see, you need to define CSS properties for all the elements. It can be grouped in
following ways:
h1,h2,p {
text-align: center;
color: blue;
}
Let's see the full example of CSS group selector.
<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, p {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1>Hello Javatpoint.com</h1>
<h2>Hello Javatpoint.com (In smaller font)</h2>
<p>This is a paragraph.</p>
</body>
</html>
Output:
Hello Javatpoint.com
Hello Javatpoint.com (In smaller font)
This is a paragraph.
Levels of CSS
Cascading Style Sheet (CSS) is used to set the style in web pages that
contain HTML elements. It sets the background color, font-size, font-family, color, … etc.
properties of elements on a web page.
There are three types of CSS which are given below:
• Inline CSS
• Internal or Embedded CSS
• External CSS
Inline CSS: Inline CSS contains the CSS property in the body section attached to the
element is known as inline CSS. This kind of style is specified within an HTML tag using
the style attribute.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 27 of 32
Computer Animation & Multimedia
Example: This example shows the application of inline-css.
<!DOCTYPE html>
<html>
<head>
<title>Inline CSS</title>
</head>
<body>
<p style="color:#009900; font-size:50px;
font-style:italic; text-align:center;">
Shree Medha Degree College
</p>
</body>
</html>
Internal or Embedded CSS: This can be used when a single HTML document must be
styled uniquely. The CSS rule set should be within the HTML file in the head section i.e.
the CSS is embedded within the <style> tag inside the head section of the HTML file.
Example: This example shows the application of internal-css.
<!DOCTYPE html>
<html>
<head>
<title>Internal CSS</title>
<style>
.main {
text-align: center;
}
.GFG {
color: #009900;
font-size: 50px;
font-weight: bold;
}
.smdc {
font-style: bold;
font-size: 20px;
}
</style>
</head>
<body>
<div class="main">
<div class="GFG">Shree Medha Degree College</div>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 28 of 32
Computer Animation & Multimedia
<div class="smdc">
Courses Offered BCA, BBA, BCom & BHM
</div>
</div>
</body>
</html>
External CSS: External CSS contains separate CSS files that contain only style properties
with the help of tag attributes (For example class, id, heading, … etc). CSS property is
written in a separate file with a .css extension and should be linked to
the HTML document using a link tag. It means that, for each element, style can be set only
once and will be applied across web pages.
Example: The file given below contains CSS property. This file saves with .css extension.
For Ex: bca.css
body {
background-color:powderblue;
}
.main {
text-align:center;
}
.GFG {
color:#009900;
font-size:50px;
font-weight:bold;
#bca {
font-style:bold;
font-size:20px;
}
Below is the HTML file that is making use of the created external style sheet.
• link tag is used to link the external style sheet with the html webpage.
• href attribute is used to specify the location of the external style sheet file.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="bca.css" />
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 29 of 32
Computer Animation & Multimedia
</head>
<body>
<div class="main">
<div class="GFG">Shree Medha Degree College</div>
<div id="bca">
Courses Offered BCA, BBA, BCom & BHM
</div>
</div>
</body>
</html>
Earlier Versions of HTML
With emerging technologies and changing industry standards, HTML has evolved
to meet these needs. Below is a brief overview of earlier HTML versions.
HTML 1.0
It is the first version of HTML language which was released in 1991. That was the basic
version of HTML language with fewer features than the latest versions.
HTML 2.0
HTML 2.0 was developed in 1995 with the intention of improving the first version. This
version supported features like forms with basic elements such as text boxes, buttons, etc.
HTML 3.2
After HTML 2.0, HTML 3.2 was released in 1997. This version provided extra features for
form elements and could make tables. Another important feature in this version was
support for CSS (Cascading Style Sheet). CSS delivers features that make HTML tags look
better and style HTML elements. Most browsers nowadays also support this version.
HTML 4.01
This version came in 1999 and provided extra support for CSS. This version supported
external styling. Now CSS files need not be embedded in the HTML file itself. Instead, They
can be included in HTML. That helped to avoid writing repetitive styles for HTML pages.
Overview of HTML5
HTML5 is the next major revision of the HTML standard superseding HTML 4.01,
XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content
on the World Wide Web.
HTML5 is a cooperation between the World Wide Web Consortium (W3C) and the Web
Hypertext Application Technology Working Group (WHATWG).
The new standard incorporates features like video playback and drag-and-drop that have
been previously dependent on third-party browser plug-ins such as Adobe Flash, Microsoft
Silverlight, and Google Gears.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 30 of 32
Computer Animation & Multimedia
Browser Support
The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all
support many HTML5 features, and Internet Explorer 9.0 will also have support for some
HTML5 functionality.
The mobile web browsers that come pre-installed on iPhones, iPads, and Android phones
all have excellent support for HTML5.
Features of HTML5
HTML5 introduces several new elements and attributes that can help you in building
modern websites. Here is a set of some of the most prominent features introduced in
HTML5.
Ö New Semantic Elements − These are like <header>, <footer>, and <section>.
Ö Forms 2.0 − Improvements to HTML web forms where new attributes have been
introduced for <input> tag.
Ö Persistent Local Storage − To achieve without resorting to third-party plugins.
Ö WebSocket − A next-generation bidirectional communication technology for web
applications.
Ö Server-Sent Events − HTML5 introduces events which flow from web server to the
web browsers, and they are called Server-Sent Events (SSE).
Ö Canvas − This supports a two-dimensional drawing surface that you can program
with JavaScript.
Ö Audio & Video − You can embed audio or video on your webpages without
resorting to third-party plugins.
Ö Geolocation − Now visitors can choose to share their physical location with your
web application.
Ö Microdata − This lets you create your own vocabularies beyond HTML5 and extend
your web pages with custom semantics.
Ö Drag and drop − Drag and drop the items from one location to another location on
the same webpage.
Ö Support for Dynamic Web Pages - Web servers send static web pages to the web
browser directly without any data modification whenever the user requests the web
page. But, with the dynamic web page feature of html5, different contents can be
shown to different users while maintaining the same design and layout. This html5
feature is helpful in areas like stock price changes and weather prediction.
Several aspects which give a dynamic feel to web pages are:
Marks: Makes stuff attractive and draws the attention of the user to it.
Time: Display the current date and time on the web page
Meter: Indicates available space on the storage drive
Progress bar: Helps to track the progress assigned to you.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 31 of 32
Computer Animation & Multimedia
Backward Compatibility
HTML5 is designed, as much as possible, to be backward compatible with existing
web browsers. Its new features have been built on existing features and allow you to provide
fallback content for older browsers.
It is suggested to detect support for individual HTML5 features using a few lines of
JavaScript.
If you are not familiar with any previous version of HTML, I would recommend that you
go through our HTML Tutorial before exploring the features of HTML5.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 32 of 32
Computer Animation & Multimedia
UNIT-2
ANIMATION
What Is An Animation?
Before we proceed further down the bright, lava-filled pit where you learn how to
create animations, let's take a step back and figure out what an animation is. Let's start with
a definition. At its most basic level, an animation is nothing more than a visualization of
change - a change that occurs over a period of time.
The Start and End States
If visualizing change is an important part of an animation, we need to create some
reference points so that we can compare what has changed. Let's call these reference points
the start state and the end state. To better explain what is going on, let's come up with an
easy-to-understand example as well.
Let's say our start state looks as follows:
You start off with a blue circle that is small and located to the left of the screen. At the end
state, your blue circle now looks sorta kinda like this:
Based just on the information you have on what our blue circle looks like in the start and
end states, what can you tell is different?
One change is the position. Our blue circle starts off on the left side of the screen. It ends up
on the right hand side. Another change is the size. Our circle goes from being small to being
much larger.
How do we make an animation out of this? If we were to just play the start and end states
repeatedly, what you would see is something that just bounces from left to right very
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 1 of 30
Computer Animation & Multimedia
awkwardly. That is pretty terrible. Just terrible. What we need is a way to smooth things out
between the start and end states. What we need is a healthy dose of interpolation.
Interpolation
Right now, what we have are two discrete states in time. At the beginning, you have
your start state. And the end, you have the end state. If you were to play this back, this
wouldn't be an animation. In order to make an animation out of what we have, we need a
smooth transition that creates all the intermediate states. This creation of the intermediate
states is known as interpolation.
This interpolation, which occurs over a period of time that you specify, would look similar
to the following diagram:
You may be wondering who specifies the interpolated states. The answer, which is probably
good news, is that your browser or HTML rendering engine will take care of the messy
details. All you need to specify is the starting state, the ending state, and the duration over
which the transition between the two states needs to occur. Once you have those three
things, you have an animation!
You will later see how adding some other ingredients into the pot such as timing functions
(easing functions) can alter how the interpolation works, but we'll get there later. For now,
just revel in this simplified generalization of what makes up an animation, put on you r best
party clothes, and get ready to meet the three flavors of animation that you will end up
using.
Animations in HTML
In HTML, there isn't just a single animation implementation (hey, that rhymes!) that
you can use. You actually have three flavors of animation to choose from, and each one is
specialized for certain kinds of tasks. Let's take a quick look at all three of them and see how
they relate to the animation definition you saw in the previous section.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 2 of 30
Computer Animation & Multimedia
1. CSS Animations (aka Keyframe Animations)
CSS Animations are your traditional animations that on some sort of performance
enhancing substance that makes them more awesome. With these kinds of animations, you
can define not only the beginning and the end state but also any intermediate states lovingly
known as keyframes:
These intermediate states, if you choose to use them, allow you to have greater control over
the thing you are animating. In the above example, the blue circle isn't simply sliding to the
right and getting larger. The individual keyframes adjust the circle's size and vertical
position in ways that you wouldn't see if you simply interpolated between the start and end
states.
Remember, even though you are specifying the intermediate states, your browser will still
interpolate what it can between each state. Think of a keyframe animation as many little
animations daisy chained together.
2. CSS Transitions
Transitions make up a class of animations where you only define the start state, end
state, and duration. The rest such as interpolating between the two states is taken care of
automatically for you:
While transitions seem like a watered down, simplified keyframe animation, don't let that
trick you. They are extremely powerful and probably my favorite animation technique to
use in my projects. You'll see more about them shortly.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 3 of 30
Computer Animation & Multimedia
3. Scripted / JavaScript Animations
If you want full control over what your animation does right down to how it
interpolates between two states, you can use JavaScript:
There are a lot of cool things you can do when you opt-out of the interpolation the browser
does for you, and you'll get a good dose of that in the tutorials that look at JavaScript
Animations in greater detail.
Introduction to CSS Animations
When creating animations on the web, you can't really go far without running
into CSS animations. What CSS animations do is pretty simple. They allow you to animate
CSS properties by having you specify what your CSS properties will do at various points in
time. These "points in time" have a very specific name. They are known as keyframes. If
you've used animation tools in the past, the word keyframes should sound familiar to you.
The keyframes you define in CSS as part of making your CSS animations work is the
equivalent of the keyframes you would have visually defined in Flash/Animate, After
Effects, or some other animation tool:
If you've never used animation tools in the past, don't worry. You won't be missing out on
much. We'll be doing all of our animating manually (like an animal!) and learning what is
going at each step. By the end of this tutorial, you'll have learned enough to create an
animation that looks as follows:
Along the way, we'll cover the animation property, the @keyframes rule, and a handful of
other topics that will set you up for cooler and more advanced things using CSS animations
in the future.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 4 of 30
Computer Animation & Multimedia
Creating a Simple Animation
The easiest (and most fun!) way to learn about CSS animations is to just get your hands
messy with using them. Go ahead and create a new HTML document and add the following
HTML and CSS to it:
<!DOCTYPE html>
<html>
<head>
<title>Intro to CSS Animations</title>
<style>
body {
padding: 50px;
}
#container {
padding: 20px;
width: 100%;
height: 250px;
background-color: #EEE;
text-align: center;
}
</style>
</head>
<body>
<div id="container">
<img id="hexagon" src="https://www.kirupa.com/images/hexagon.svg"/>
</div>
</body>
</html>
Take a moment to look at what you just added. As web pages go, there isn't anything too
complex or crazy going on here. The main thing I want you to note is that we have an image
element, and it has an id value of hexagon:
<div id="container">
<img id="hexagon" src="https://www.kirupa.com/images/hexagon.svg"/>
</div>
We'll be coming back to this element in a little bit, so don't forget about it!
Now, before we move on to the next step, go ahead and preview this page in your browser.
If everything worked right, you will see a happy hexagon shape, standing boringly still:
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 5 of 30
Computer Animation & Multimedia
Let's fix the boredom by animating our hexagon shape. To do this, we are going to create a
CSS animation. To create a CSS animation, you will need to complete two steps:
i. Set the animation property
ii. Define the keyframes that specify exactly how and when CSS properties get
animated
We'll tackle both of these steps one at a time. First, we'll deal with our animation property.
In your style block where your style rules currently live, add the #hexagon style rule below
where your #container style rule lives:
#hexagon {
animation: bobble 2s infinite;
}
The details of what is going inside this style rule isn't important for now, for we'll have time
to get acquainted with it later. Instead, let's go to our next step and specify what our
animation does by adding the keyframes. Go ahead and add the following @keyframes style
rule just below where where your #hexagon style rule lives:
@keyframes bobble {
0% {
transform: translateY(10px);
}
50% {
transform: translateY(40px);
}
100% {
transform: translateY(10px);
}
}
Once you've added this style rule, go ahead and preview your page now. You should see
your happy hexagon shape bobbling around happily as if it has no care in the world.
Awesome!
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 6 of 30
Computer Animation & Multimedia
<!DOCTYPE html>
<html>
<head>
<title>Intro to CSS Animations</title>
<style>
body {
padding: 50px;
}
#container {
padding: 20px;
width: 100%;
height: 250px;
background-color: #EEE;
text-align: center;
}
#hexagon {
animation: bobble 2s infinite;
}
@keyframes bobble {
0% {
transform: translateY(10px);
}
50% {
transform: translateY(40px);
}
100% {
transform: translateY(10px);
}
}
</style>
</head>
<body>
<div id="container">
<img id="hexagon" src="https://www.kirupa.com/images/hexagon.svg"/>
</div>
</body>
</html>
What Just Happened
What you just did was define a CSS animation that caused your hexagon shape to
bobble around. In our rush to get the example working, we didn't stop to examine what
exactly is going on at each step. We just ran screaming through it. Let's take a few moments
to go back and revisit what we just did and learn more about why we did it.
The first thing we will look at is the animation property itself:
animation: bobble 2s infinite;
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 7 of 30
Computer Animation & Multimedia
The animation property is responsible for setting your animation up. In the shorthand
variant that you see (and will commonly use), you will specify three values:
i. The name of the animation
ii. The duration
iii. The number of times your animation will loop
You can see these values in our animation declaration. The name of our animation is
called bobble, the duration of the animation is 2 seconds, and it is set to loop
an infinite number of times.
As you can see, the animation declaration doesn't really contain much in terms of details on
what gets animated. It sets the high-level definition of what your animation will do, but the
actual substance of a CSS animation actually resides in its @keyframes rule.
Let's look at our @keyframes rule to learn more:
@keyframes bobble {
0% {
transform: translateY(10px);
}
50% {
transform: translateY(40px);
}
100% {
transform: translateY(10px);
}
}
The first thing to notice when you look at our @keyframes rule is how it looks. On the
outside, it contains the @keyframes declaration followed by a name:
@keyframes bobble {
0% {
transform: translateY(10px);
}
50% {
transform: translateY(40px);
}
100% {
transform: translateY(10px);
}
}
On the inside, it contains style rules (aka the actual keyframes) whose selectors are
percentage values (or the keywords from and to...but ignore that for now):
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 8 of 30
Computer Animation & Multimedia
@keyframes bobble {
0% {
transform: translateY(10px);
}
50% {
transform: translateY(40px);
}
100% {
transform: translateY(10px);
}
}
These style rules, often referred to as keyframe style rules, are pretty much what you would
expect. They just contain CSS properties such as transform whose value will get applied
when the rule becomes active.
Now, what I have just explained is the part that easily makes sense. Here is where things
could get a little bit confusing. Despite the animation property being declared in another
style rule and your keyframes being declared in their own @keyframes rule, they are very
much tied at the hip and don't really function without the other one being present.
Let's start by first looking at how the animation property and the @keyframes rule are tied together.
The Name
The name you give your @keyframes rule acts as an identifier the animation property uses
to know where the keyframes are:
#hexagon {
animation: bobble 2s infinite;
}
@keyframes bobble {
0% {
transform: translateY(10px);
}
50% {
transform: translateY(40px);
}
100% {
transform: translateY(10px);
}
}
It isn't a coincidence that our animation property refers to bobble, and the name of
our @keyframes rule is also bobble. If there is ever an inconsistency in the names, your
animation will not work.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 9 of 30
Computer Animation & Multimedia
Duration and the Keyframes
So we now know how our animation property is made aware of its keyframes. That
solves one mystery. The next (and more complicated!) mystery that we are going to now
look at is the one surrounding when a particular keyframe style rule actually becomes
active.
As you recall, when you defined the keyframe style rules inside your @keyframes rule, our
selector wasn't an actual time value. It was a percentage value:
@keyframes bobble {
0% {
transform: translateY(10px);
}
50% {
transform: translateY(40px);
}
100% {
transform: translateY(10px);
}
}
What these values represent is the percentage of the animation that has completed. Using
the values from our example, the 0% keyframe represents the start of our animation. The
50% keyframe represents our animation's mid-way point. The 100% keyframe represents
the end of our animation.
When we think of things happening in an animation, we don't think in terms of percentage
values. We typically think in terms of points in time. To rationalize the differences between
what CSS expects and what we humans expect, we need to understand the role the duration
value plays. The duration value not only specifies the total length of our animation. It also
helps specify the time a particular keyframe will become active.
Taking our 2-second long animation as an example, below is a diagram that illustrates how
our percentage values map to units of time:
The 0% keyframe becomes active at the beginning after 0s have elapsed. The 50% keyframe
becomes active after 1 second has elapsed. The 100% keyframe becomes active at the end
once 2 seconds have elapsed.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 10 of 30
Computer Animation & Multimedia
Looping
The third value you specify for the animation property determines the number of
times your animation will play. You can specify an actual number, or you can specify the
word infinite to have your animation play forever and ever...and ever! That's all there is to
this value. Not particularly exciting, is it? :P
The Longhand Version
The animation property isn't always as concise as what we've seen here. There is a longhand
variant where you can specify the animation-related properties individually. The longhand
variant for the shorthand version we've seen so far looks as follows:
#hexagon {
animation-name: bobble;
animation-duration: 2s;
animation-iteration-count: infinite;;
}
With the animation-name property you specify the name of the @keyframes rule your
animation relies on to run. Your animation's duration is set with the animation-
duration property, and you specify how many times you want the animation to loop with
the animation-iteration-count property. There are a bunch more properties where these
came from, and we'll cover all of them in a little bit.
Detailed Look at the CSS Animation Property The animation property is a whole lot more feature-
filled than what we've just seen. Now that you got your feet wet with creating an animation, let's do
something less exciting and learn about all that the animation property brings to the table. To help
with learning more about it, let's first expand our shorthand property and look at the properties in
their expanded form. Our shorthand version, as you’ve seen many times already, looks as follows:
animation: bobble 2s infinite;
Its expanded, longhand version will look like this:
animation‐name: bobble; animation‐duration: 2s;
animation‐iteration‐count: infinite;
Pausing and Resuming an Animation By default, your animation will start once the style rule
containing your animation property becomes active. For our simple case, this basically means the
moment the page loads and the CSS is parsed. First, let's loosely visualize a 2 second long animation
that is set to loop infinitely as follows:
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 11 of 30
Computer Animation & Multimedia
Detailed Look at the CSS Animation Property
The animation property is a whole lot more feature-filled than what we've just seen.
Now that you got your feet wet with creating an animation, let's do something less exciting
and learn about all that the animation property brings to the table. To help with learning
more about it, let's first expand our shorthand property and look at the properties in their
expanded form. Our shorthand version looks as follows:
animation: bobble 2s infinite;
Its expanded version will look like this:
animation-name: bobble;
animation-duration: 2s;
animation-iteration-count: infinite;
The three properties our shorthand version expands to are animation-name, animation-
duration, and animation-iteration-count. What these properties do should be ingrained in
your mind by now, so let's just move on to tasks that use the properties we haven't seen yet
- properties such as: animation-play-state, animation-delay, animation-
direction, animation-fill-mode, and animation-timing-function.
Pausing and Resuming an Animation
By default, your animation will start once the style rule containing your animation property
becomes active. For our simple case, this basically means the moment the page loads. First,
let's loosely visualize a 2 second long animation that is set to loop infinitely as follows:
Each yellow rectangle represents one iteration of your animation. If you put each iteration
of the animation side by side, you get something that looks like what I've shown above.
Once the animation starts, it won't stop until it reaches the end. If your animation is set to
loop, it will just keep running by starting over from the beginning once it hits the end. It is
this looping that is represented as a separate yellow rectangle each time. Our current bobble
animation is living proof of this behavior.
Sometimes, you may not want that behavior. If you want your animation to not play
immediately once the style rule containing your animation definition becomes active or if
you want to pause your animation in the middle, you can fiddle with the animation-play-
state property. This property allows you to toggle whether your animation plays or not by
reacting to the running value or the paused value.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 12 of 30
Computer Animation & Multimedia
By default, the animation-play-state property is set to running. You can set the value
to paused to stop your animation dead in its tracks:
animation-play-state: paused;
When the animation is paused, it retains whatever the last computed value the animation
had:
It is almost as if time just stood still. You can resume it by setting the animation-play-
state property back to running. There is no sudden restart where the animation goes back
to the 0% mark before resuming:
Your animation smoothly picks up from where it left off just like what you would expect if
you used the Play and Pause functionality on a media player.
Delaying and Offsetting the Animation
If you want your animation to play but not really do anything for a period of time,
you will want to meet the animation-delay property. This property allows you to specify
the number of seconds of time will elapse before your animation starts to run.
animation-delay: 5s;
A delay isn't a case where the 0% keyframe gets hit and then you wait for 5 seconds. The
delay occurs before the 0% keyframe from your first iteration is even hit:
Once your animation starts running, the delay value never comes into play again. Every
subsequent iteration (if there are any left) of your animation just flows seamlessly from the
end of one to the beginning of the other.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 13 of 30
Computer Animation & Multimedia
Now, here is something else you can do with this property. Instead of specifying a positive
time value for animation-delay, you can actually specify a negative time value as well:
animation-delay: -.25s;
When you specify a negative value, your animation starts immediately but offset by the
duration that you specified. Here is what an animation-delay of -.25s would look like:
The negative sign acts as a signal to tell your browser to treat this value as an offset instead
of a delay. Yes, that is a little strange, especially given that this property is still
called animation-delay, but I am merely the messenger here. Something less strange - if you
specify an offset that is greater than the duration of a single iteration of your animation, that
isn't a problem at all. Your animation will just start at whatever point in whichever iteration
the starting point falls at. Just make sure you have enough iterations to account for the
starting point in a future iteration. If you don't have enough iterations and you specify a
large offset, your animation simply won't run.
Hold My Keyframe Properties, Please!
If you don't tell your animation to loop, you will notice that once your animation
ends, any properties the keyframes set are removed and your elements return to a pre-
animation state. This is because the properties applied by your keyframes are transient.
They exist while the keyframes are active, but at any time outside that window, those
property values are not maintained. If you didn't intend for that behavior, your animation
may seem to suddenly jump into position at the start or suddenly reset after it has run to
completion. Let's examine these two cases with a little more specificity and then look at how
to change the default behavior.
Waiting to Start
The first case occurs when you are dealing with a animation-delay set. For example, let's say
you have a 5s delay specified:
For the five seconds your animation is waiting, your keyframes are not active yet. Any
properties the first keyframe contains will not get applied while the delay is active.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 14 of 30
Computer Animation & Multimedia
Animation is Done
The second case is when your animation has run to completion. Let's say you specified your
animation to loop three times:
At the end, any properties specified by the last keyframe on the 3rd iteration will disappear.
Your animated elements will return to a state where there was no evidence of an animation
ever having existed.
Meet animation-fill-mode
If you want your starting keyframe's properties to apply during a delay or your last
keyframe's properties to be retained after your animation has ended, you can set
the animation-fill-mode property. You can set its value to be:
i.none
There is no faking the property values here. If you want the a keyframe's property
values to apply, your keyframe must be active.
ii.forwards
After your animation has run to completion, any property values the animation had at
the end will be maintained.
iii.backwards
The animation will apply the property values from the starting keyframe even if that
keyframe is not active yet.
iv.both
This is the ultimate solution. Your animation will apply the property values of the first
keyframe at the beginning and maintain the property values of the last keyframe at the
end.
The animations I have created loop forever and don't have delays at the beginning. Many
animations I have created also do not have a significant difference in property values
between the starting keyframe, the ending keyframe, and the animated elements in their un-
animated state. Because of that, I've never really had to stay up at night worrying, so don't
feel pressured by your peers to declare the animation-fill-mode property if you don't want
to.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 15 of 30
Computer Animation & Multimedia
Reversing an Animation (or Alternating Directions)
Now, let's look at a slightly trippy property. Your animations play sequentially from 0% to
100% by default. You have the ability to change this behavior by setting the animation-
direction property to either normal, reverse, alternate, or alternate-reverse.
Both normal and reverse should be straightforward to figure out what they do, so let's look
at the more interesting values: alternate and alternate-reverse.
When you set the animation-direction to alternate-reverse, your animation starts off
normal. Starting with the second iteration, it plays in reverse and alternates between normal
and reverse from there on out:
Setting your animation-direction to just alternate has a similar but slightly different
behavior:
Your animation starts off in reverse and alternates between normal and reverse from that
point on.
At Easing, Soldier!
The last animation-related property we have to cover is animation-timing-function. This
function allows you to specify how your animation interpolates the property values
between the beginning and the end .
The Animation Shorthand
What we have primarily looked at so far are the longhand properties for declaring your
animation:
#somethingSomethingDarkSide {
animation-name: deathstar;
animation-duration: 25s;
animation-iteration-count: 1;
animation-play-state: paused;
animation-delay: 0s;
animation-direction: normal;
animation-fill-mode: both;
animation-timing-function: ease-out;
}
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 16 of 30
Computer Animation & Multimedia
Some of you may prefer using shorthand properties where all of the properties and their
values are specified inside the animation property itself. In fact, as you know, our very own
bobble animation is represented in its shorthand variant:
animation: bobble 2s infinite;
All of the longhand properties you see above can be represented in their shorthand form -
just good luck in remembering it all. If you don't doubt me, here is what the mapping looks
like:
animation: <animation-name> <animation-duration> <animation-timing-function>
<animation-delay> <animation-iteration-count> <animation-direction> <animation-fill-
mode>;
Simply substitute the appropriate value for the property that is displayed inside the angled
brackets. Note that the animation-play-state property is not something that can be
represented in shorthand. You will have to explicitly spell out that property and its value.
Anyway, to put our longhand example into shorthand, here is how everything would look:
#somethingSomethingDarkSide {
animation: deathstar 25s ease-out 0s 1 normal both;
animation-play-state: paused;
}
Is the shorthand version more compact than the equivalent longhand version? Absolutely!
Is it more understandable? That's a tough one to answer and entirely based on your (or your
team's) preference.
I generally like to use the shorthand version for specifying the animation-name, animation-
duration, and animation-timing-function because that is easy for me to remember. Once I
go beyond three property values, I have to start searching through the documentation on
what the additional values refer to.
Your mileage may vary with regards to your views on longhand vs. shorthand properties,
so use whatever you feel most comfortable with. And...with that brilliant piece of insight,
it's time to bid adieu to this detailed look at the animation property and focus on other sights
on our never-ending scenic trip through animation country.
Looking at the Keyframes
A bulk of our time so far has been spent looking at the animation property and how it affects
your overall...animation. The real heroes of a CSS animation are t he keyframes, so let's
devote some more attention to them in this section.
Say hello (again) to the bobble keyframes:
@keyframes bobble {
0% {
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 17 of 30
Computer Animation & Multimedia
transform: translate3d(50px, 40px, 0px);
animation-timing-function: ease-in;
}
50% {
transform: translate3d(50px, 50px, 0px);
animation-timing-function: ease-out;
}
100% {
transform: translate3d(50px, 40px, 0px);
}
}
I mentioned earlier that an individual keyframe is very similar to a style rule. You put CSS
properties inside it and those properties become active when the selector for that keyframe
becomes active. The thing to note is that not every CSS property can be specified inside a
keyframe. The only properties you can specify are the animatable CSS properties and
the animation-timing-function.
This isn't necessarily bad news, for I'm pretty sure that the property you actually want to
use inside your keyframe falls under the list of properties that are animatable. You can view
the full list of animatable properties here and some additional ones here (note the value of
the column marked Anim.)
The last thing to look at is the animation-timing-function property that you can specify on
a keyframe as well. The effects of this property apply as you transition from your current
keyframe over to the next one. Taking our example, at the 0% keyframe, we have
our animation-timing-function set to ease-in:
@keyframes bobble {
0% {
transform: translate3d(50px, 40px, 0px);
animation-timing-function: ease-in;
}
50% {
transform: translate3d(50px, 50px, 0px);
animation-timing-function: ease-out;
}
100% {
transform: translate3d(50px, 40px, 0px);
}
}
This timing function will be active as your animation rolls from 0% to the next keyframe at
the 50% mark. Likewise, the animation-timing-function delcared at the 50% keyframe will
be active as you animate from the 50% mark to 100%. Given that the timing function works
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 18 of 30
Computer Animation & Multimedia
between your current keyframe and the next keyframe, declaring a timing function at the
100% keyframe wouldn't make too much sense.
Reusing Keyframes
The last thing I want to talk about is using the same keyframes for another animation
declaration. I lamented earlier how the disconnected nature of the animation property
declaration from the actual @keyframes rule makes working with animations a bit clunky.
Even in clunky things, there are some nice things you could do if you try hard enough.
One such thing is being able to reuse the same keyframes for another declaration of
the animation property. It may be hard to see what I mean by this, so let's just extend our
current example to highlight what I am talking about.
In your current HTML document that contains only a single cloud that is bouncing, go
ahead and add the following highlighted lines:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Bouncing Clouds</title>
<script src="https://www.kirupa.com/js/prefixfree.min.js"></script>
<style>
#mainContent {
background-color: #A2BFCE;
border-radius: 4px;
padding: 10px;
width: 600px;
height: 300px;
overflow: hidden;
}
.cloud {
position: absolute;
}
#bigcloud {
animation: bobble 2s infinite;
margin-left: 100px;
margin-top: 15px;
}
#smallcloud {
animation: bobble 4s infinite;
margin-top: 65px;
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 19 of 30
Computer Animation & Multimedia
margin-left: 200px;
}
@keyframes bobble {
0% {
transform: translate3d(50px, 40px, 0px);
animation-timing-function: ease-in;
}
50% {
transform: translate3d(50px, 50px, 0px);
animation-timing-function: ease-out;
}
100% {
transform: translate3d(50px, 40px, 0px);
}
}
</style>
</head>
<body>
<div id="mainContent">
<img id="bigcloud" alt="#" class="cloud" height="154"
src="https://www.kirupa.com/images/bigCloud.png" width="238">
<img id="smallcloud" alt="#" class="cloud" height="103"
src="https://www.kirupa.com/images/smallCloud.png" width="158">
</div>
</body>
</html>
Once you have added both the highlighted #smallCloud style rule and the
second img element, go ahead and preview your page. If everything was done correctly,
you will now see two clouds happily bouncing away...just like what you saw from the
working example at the beginning of this tutorial.
Now that your example works, let's look at how we were able to do this. The trick lies in
the animation declaration in your #smallCloud style rule:
#smallcloud {
animation: bobble 4s infinite;
margin-top: 65px;
margin-left: 200px;
}
Notice that we are referencing the exact same @keyframes rule whose name is bobble. The
only difference between this animation declaration and the animation declaration in the
#bigCloud style rule that we have been looking at is the duration. The duration of the
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 20 of 30
Computer Animation & Multimedia
animation that applies to your small cloud is 4 seconds - twice as long as the duration of the
animation that applies to your large cloud:
#bigcloud {
animation: bobble 2s infinite;
margin-left: 100px;
margin-top: 15px;
}
What this means is that the properties you defined in your bobble keyframes apply just the
same for both our clouds. The only difference is that in one animation these keyframes run
through in 2 seconds, and in the other animation, these keyframes run through at 4 seconds:
This independence between the keyframes and the animation declaration allows you to get
away with doing something like this. Any alterations you make in the declaration of
your animation property will affect your keyframes on a superficial level - just like you saw
here with the duration. Every animation property I explained a few sections ago can be set
to alter how your keyframes behave without having to directly touch your keyframes.
Declaring Multiple Animations
The last thing (ok, for real this time) we will quickly look at is how to declare multiple
animations in the same animation property. In your shorthand declaration, simply comma
separate each of your animations as shown below:
#oppaGangnamStyle {
animation: hey 2s infinite, sexy 1s infinite, lady 5s infinite;
}
Notice that each animation is pointing to a different @keyframes rule. If for whatever reason
you decide to point to the same @keyframes rule from within the same animation property
declaration, based on CSS order precedence, the last one you declared will win.
When declaring your animations in longhand, you would do something that looks as
follows:
#oppaGangnamStyle {
animation-name: hey, sexy, lady;
animation-duration: 2s, 1s, 5s;
animation-iteration-count: infinite;
}
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 21 of 30
Computer Animation & Multimedia
Again, this should be pretty straightforward as well. Everything is comma separated in CSS,
so when in doubt about how to declare multiple values for a property that supports multiple
values, just add a comma.
All About CSS Transitions
In CSS, when you change the value of a property, the change is sudden. For example,
let's say that you have the following CSS where on hover,
the transform property's translate3d function has a different value:
#box img {
transform: translate3d(0, -350px, 0);
}
#box img:hover {
transform: translate3d(0, 0px, 0);
cursor: pointer;
}
This value is responsible for pushing the vertical position of an image up by 350 pixels. To
see this in action, hover over the image of the HTML5 logo in the following example:
Notice what happened when you hovered over the image. At the moment you hovered, the
image changed to show something different. This change wasn't gradual. It was sudden.
One moment you are seeing the HTML5 logo in a black background. The next moment you
are seeing the same logo in a yellow background.
This is where a transition can do some nifty things. Transitions slow down the sudden
change in properties. They allow you to specify how long a particular property change will
take place. They allow you to specify what kind of easing will be applied in going from the
current property value to another. Transitions basically allow you to animate the property
value changes.
With a transition applied, hover over the same logo in the following example:
This time around, instead of seeing a sudden change in the image, you can actually visualize
the intermediate positions as well. You see a gradual change as the image slides up. You see
an animation. If you interrupt the slide by hovering away before the logo reaches its final
position, notice that the transition simply animates back to its original state without any
fuss. Isn't that pretty awesome?
Adding a Transition
Now that you have a pretty good idea of what a transition is and what it is capable
of, let's go ahead and use one. To follow along, create a new HTML document and
copy/paste the following HTML into it:
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 22 of 30
Computer Animation & Multimedia
<!DOCTYPE html>
<html>
<head>
<meta content="en-us" http-equiv="Content-Language">
<meta charset="utf-8">
<meta content="stuff, to, help, search, engines, not" name="keywords">
<meta content="What this page is about." name="description">
<meta content="An Interesting Title Goes Here" name="title">
<title>An Interesting Title Goes Here</title>
<style>
body {
background-color: #FFF;
margin: 30px;
margin-top: 10px;
}
#box {
width: 350px;
height: 350px;
border: 5px black solid;
overflow: hidden;
background-color: #F2F2F2;
}
#box img {
transform: translate3d(0, -350px, 0);
}
#box img:hover {
transform: translate3d(0, 0px, 0);
cursor: pointer;
}
</style>
</head>
<body>
<div id="box">
<img height="700" src="//www.kirupa.com/images/html5_slider.png" width="350"></div>
<script src="//www.kirupa.com/prefixfree.min.js"></script>
</body>
</html>
If you preview this document, you will see a picture of our HTML5 logo over a yellow
background. When you hover over this image, the picture will suddenly change to show
the same logo over the black background. If this sounds familiar, it should be. This is
identical to the example without the transition you saw a few paragraphs earlier!
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 23 of 30
Computer Animation & Multimedia
What we are going to do is add a CSS transition to make the change in the image's position
look smooth. Take a look at your #box img style rule:
#box img {
transform: translate3d(0, -350px, 0);
}
Just above the transform property declaration, add the following highlighted line that
contains our transition declaration:
#box img {
transition: transform .5s ease-in;
transform: translate3d(0, -350px, 0);
}
Once you've added the highlighted line, preview this document in your browser again.
Hover over the image, and (if everything worked properly) you will now see your image
gently slide from one position to another. That's all there is to it. In the next few sections,
let's look in detail at the line you added and learn more about transitions than you ever
thought you needed to know.
What About the Vendor Prefixes?
The transition property is still pretty new, so a lot of browsers require it to be vendor
prefixed in order to have it work. Do not clutter up your markup with them. Instead, use
something like the -prefix-free library that this example uses to keep your markup simple
while still allowing older browsers to be able to view your transition.
Looking at Transitions in Detail
Now that you have a working example that uses a transition, let's try to understand
why it works. To reuse a graphic that I used in my Introduction to Animation in
HTML tutorial, a transition basically works by interpolating the points between a start state
and an end state:
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 24 of 30
Computer Animation & Multimedia
The start state is defined by whatever value a CSS property you are wishing to transition
has initially:
#box img {
transform: translate3d(0, -350px, 0);
}
The end state is the final value of that same CSS property:
#box img:hover {
transform: translate3d(0, 0px, 0);
cursor: pointer;
}
Normally, this jump from the start state to the end state is sudden as you saw a few times
already. With a CSS transition in place, though, that jump is gradual and defined entirely
by your duration and whatever easing / timing function your transition specified:
transition: transform .5s ease-in;
A typical CSS transition defines the following three properties:
i. The property to apply the transition to
ii. How long the transition will last
iii. What kind of a timing function (aka easing function) to use
If you look at the transition you added in the previous section, you can see how what we
specified maps to these three properties perfectly...like a glove:
What you see above is the shorthand declaration for the transition property. As shorthand
properties go, the values it specifies map to CSS properties of their own, so let's look at these
transition-related properties in greater detail.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 25 of 30
Computer Animation & Multimedia
Transition Property
The first value you specify in your transition declaration maps to the transition-
property CSS property. Here, you specify the CSS property you want your transition to
listen for changes on:
Given what we specified in our example, any changes to the transform property will be
detected by our transition and animated appropriately. Depending on what you are wishing
to transition, you will specify a different CSS property as needed.
Note: Animatable CSS Properties Only Please
One thing to note is that you can't just specify any CSS property for your transition-
property. The property has to animatable. That might sound like a major buzzkill, but it
really isn't. For the most part, almost any CSS property you want to use as part of a transition
is probably animatable already.
You can view the full list of animatable properties here and some additional ones here (note
the value of the column marked Anim.)
Now, if you don't want to limit your transition to listen for changes on just a single property
and don't want to deal with managing each property separately (as I will explain later), you
can specify the keyword all:
transition: all .5s ease-in;
By specifying all, any change to any CSS property that your transition applies to will
automatically transition. I generally don't recommend using the all keyword unless you
really are planning on wanting a transition for changes occurring on different properties.
The reason is that there is a slight performance hit with your browser having to poll every
CSS property to see if a change has occurred as opposed to checking a select few properties
that you specify.
Transition Duration
The second value in our transition declaration maps to the transition-duration property.
This property expects a numerical value that specifies how long the transition will run:
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 26 of 30
Computer Animation & Multimedia
This is a pretty simple one. To have your transition run for a long time, specify a large
duration value. To have a quick transition, specify a small value such as the .5 seconds
specified in our example.
Transition Timing Function (Easing Function)
The third value maps to the transition-timing-function property whose value specifies the
rate at which your property values change from their initial value to their final value:
This rate change is more formally defined as a timing function. By default, your values
change linearly with time:
This results in a transition that neither seems to speed up or slow down. It is just constant.
You can override this default behavior and specify something more interesting:
This overriding is done by specifying a timing function that will suit your needs. The timing
functions you can specify are:
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 27 of 30
Computer Animation & Multimedia
• ease
• linear
• ease-in
• ease-out
• ease-in-out
• step-start
• step-end
• steps()
• cubic-bezier()
Depending on the function you choose, your transition may seem like it is accelerating,
decelerating, or doing a combination of both
One More Thing: Delaying the Transition
You are not done just yet. There is actually a lesser used fourth value that you can set
on your transition declaration, and this value maps to the transition-delay property:
As you can imagine based on the property name, the duration you specify determines how
long to wait before starting your transition. If that is all this property did, it would be pretty
boring...as infrequently used properties go. This property does something extra. This
property's behavior is a little different depending on the sign value of the duration you
specify.
Let's say you specify a positive value:
transition: all .5s ease-in .1s;
A positive value specifies how long your transition will wait before kicking in. This is what
you would expect this property to do. For example, given the above declaration, our
transition will wait for .1 seconds before starting.
A negative value does something a bit different:
transition: all .5s ease-in -.1s;
With a negative value, what you are specifying is the point in time in the middle of the
transition to start from. If your transition is .5 seconds and your transition delay is -.1
seconds, your transition will (rudely!) start in the middle of the .1 second mark.
In general, setting the transition delay property is something I haven't seen too much of in
the wild. Given what the positive and negative variations of it do, I am not sure when I
would have a need to use them either.
The Longhand Properties
In the previous section, we only looked at the shorthand version of
our transition declaration while only tipping our hat to the actual CSS properties the
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 28 of 30
Computer Animation & Multimedia
shorthand values map to. Our shorthand declaration expanded into the longhand version
looks as follows:
transition-property: all;
transition-duration: .5s;
transition-timing-function: ease-in;
transition-delay: .1s;
To more properly introduce them, the four transition-related properties are the transition-
property, transition-duration, transition-timing-function, and transition-delay.
Of course, the observed behavior between using the shorthand version or the longhand
version is no different. They both create the same end result, so which you prefer to use is
entirely up to you...sort of. The next section provides some of my guidance.
Longhand Properties vs. Shorthand Properties
In general, I prefer the shorthand version because of its compactness. The only time
I don't use the shorthand property is when I plan to modify my transition using JavaScript.
Let me elaborate on this further.
Let's say my transition is declared in my CSS as follows:
transition: width 1s ease-out;
I have some code that changes the duration of my transition on the fly. This code does
something as follows:
obj.style.transitionDuration = ".2s";
If you let this code execute, what do you think our transition will look like. Logically, since
you only changed the transition's duration to .2 seconds, you would expect the transition to
virtually look as follows:
transition: width .2s ease-out;
What actually happens is quite illogical. By setting the transitionDuration property, the
entire transition goes away. All you see is evidence of your transitionDuration being set, but
the original transition declaration and any values its shorthand properties contained are
gone. Completely gone!
The proper way to deal with this situation is to set the transition property in its entirety
again:
obj.style.transition = "transition: all " + myDuration + "s ease-in;";
The end result is a string that looks exactly like our initial transition declaration defined in
the CSS. To me, this looks awkward. The way I work around this is by having all of the
transition properties declared separately as longhand variants:
transition-property: width;
transition-duration: 1s;
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 29 of 30
Computer Animation & Multimedia
transition-timing-function: ease-out;
This way, if I want to modify the duration using JavaScript, only the style declaration
for transition-duration will be overwritten. I don't have to worry about the existing non-
duration properties getting obliterated with me having to rebuild them.
Working with Multiple Transitions...and So On
The last thing we are going to talk about is something that I briefly mentioned earlier around
having multiple transitions, listening to multiple transition properties, and so on. Let's
quickly look at some of the common cases in this section.
Multiple Transitions
Declaring multiple transitions is pretty straightforward. When using
the transition shorthand, separate each transition's property values with a comma:
transition: width .5s ease-in, border-radius 1s linear;
For the longhand form, simply tackle on any additional values as needed to the appropriate
transition property:
transition-property: width, border-radius;
transition-duration: .5s, 1s;
transition-timing-function: ease-in, linear;
If you have a mismatched number of values, the standard behavior for ensuring your CSS
properties have well-defined values kicks in.
Listening to Multiple Properties
If you want to listen to a handful of properties individually, just use the longhand
version and list all of the properties you want your transition to listen to in the transition-
property property:
transition-property: width, border-radius, background-color;
transition-duration: .5s;
transition-timing-function: ease-out;
What you've basically defined is three separate transitions (one for each transition-property
value) that each have a duration of .5 seconds with an ease-out timing function specified.
This is all should be pretty straightforward.
The transitionEnd Event
The last thing (for real this time) we are going to mention is the transitionEnd event.
When a transition has run to completion, the elements affected by the transition fire
the transitionEnd event. There are a lot of cool things you can do by reacting to this event,
but I won't be explaining it here. Instead, all of those cool things are covered in great detail
in the transitionEnd Event tutorial there.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 30 of 30
Computer Animation & Multimedia
UNIT-3
HTML5 - SVG
SVG
HTML5 SVG( Scalable Vector Graphics) is the new way to add graphics on your
Webpage. SVG can create Vector based drawing and objects like lines, rectangle,
circle, polygons, text so on.
Unlike bitmap images (jpg, png and gif), they can increase width and height without blur.
They are even light weighted as compared to bitmap images.
HTML5 SVG Advantages of SVG: 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.
Differences between HTML SVG and HTML Canvas:
• SVG is a language for describing 2D graphics in XML whereas Canvas draws 2D
graphics, on the fly with JavaScript.
• If attributes of an SVG object are changed, the browser can automatically re-render
the shape whereas Canvas is rendered pixel by pixel. In canvas, once the graphic is
drawn, it is forgotten by the browser.
• SVG is resolution independent whereas CANVAS is resolution-dependent.
• SVG supports event handlers whereas CANVAS doesn’t have support for event
handlers.
HTML5 SVG
SVG is a tag in html5 to create svg elements. SVG is an inline-block level element.
Inside svg element, child tag of svg like rect, circle, polygon, text, g( group ), ellipse are
created. Default width of svg element is 300 and default height is 150. We can change width
and height of svg element using width and height attributes.
SVG View
This is SVG Element.Default width of svg is 300,height is 150 andfill (background
color) is transparent.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 1 of 10
Computer Animation & Multimedia
SVG Code
<svg style="border:1px solid #ccc">
</svg>
What is an SVG file? How to open or convert the image file format
• SVG is short for Scalable Vector Graphics, a resolution-independent file format for
images.
• This file format is frequently used for line art like logos and diagrams.
• You can view an SVG file in any web browser, edit it in Adobe Illustrator, or convert
it to another file format in Adobe Photoshop.
• SVG is an acronym for a Scalable Vector Graphics file, commonly used in graphics
programs like Adobe Photoshop and Adobe Illustrator. It's considered a resolution-
independent file format, because you can scale the image up to any size without
losing image quality. You can open SVG files in a variety of programs and also
convert it to other formats if needed.
How to open an SVG file
While SVG graphics are not commonly used outside of graphics professionals, the
files are easily opened and viewed using lots of common software.
The easiest way to view an SVG file is within a web browser. Because SVG uses XML
— a text-based markup language similar to HTML — any modern web browser can display
an SVG file. Just drag your SVG file to a browser like Chrome, Firefox, Safari or Microsoft
Edge and the image should appear in a new tab. You won't be able to edit the image,
though.
You can open an SVG file in any modern browser by dragging it into the browser
window.
You can also open an SVG file in many graphics programs. If you want to be able to
edit the image in its native vector format, you'll need to use a program like Adobe Illustrator.
If you use Photoshop, the image will instead be automatically converted to a bitmap graphic
at a specific size — see the next section for details.
How to convert an SVG file
Because SVG is a specialized file format, you might want to convert it to a bitmap file
like JPG or PNG so you can more easily use it in other applications. One way to do that is
with Adobe Photoshop — when you open an SVG in Photoshop, the image is automatically
converted to a bitmap graphic at a size you specify. Here's what to do:
1. In Photoshop, click File and choose Open.
2. Find the SVG file and choose Open.
3. In the Rasterize SVG Format window, choose the size that you want the image to be
converted to and click OK.
4. When you open an SVG file in Photoshop, it's converted to bitmap, so you can then
easily save it as a JPG.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 2 of 10
Computer Animation & Multimedia
5. Make any additional changes you like to the graphic.
6. Choose File, then Export, and then Export As.
7. In the Export As window, choose the kind of file you want (like JPG) to create and
click Export.
8. Choose a location for the file and click Save.
If you don't have access to a program like Photoshop or just want a quick and easy way
to convert an SVG file, you can use an online tool like Convertio.
To use Convertio:
1. 1. Click Choose Files and select your SVG file.
2. 2. In the drop-down menu to the right of to, choose the file format you want to
convert it to (such as JPG).
3. 3. Click Convert.
4. 4. After a short wait, the file will be completed. Click Download and save the file to
your computer.
Viewing SVG Files
Most of the web browsers can display SVG just like they can display PNG, GIF, and
JPG. Internet Explorer users may have to install the Adobe SVG Viewer to be able to view
SVG in the browser.
Embedding SVG in HTML5
HTML5 allows embedding SVG directly using <svg>...</svg> tag which has
following simple syntax −
<svg xmlns = "http://www.w3.org/2000/svg">
...
</svg>
Firefox 3.7 has also introduced a configuration option ("about:config") where you can enable
HTML5 using the following steps −
• Type about:config in your Firefox address bar.
• Click the "I'll be careful, I promise!" button on the warning message that
appears (and make sure you adhere to it!).
• Type html5.enable into the filter bar at the top of the page.
• Currently it would be disabled, so click it to toggle the value to true.
Now your Firefox HTML5 parser should be enabled and you should be able to experiment
with the following examples.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 3 of 10
Computer Animation & Multimedia
HTML5 − SVG Circle
SVG Circle can create circle inside an SVG tag. Circle tag can have cx ( center from
x), cy ( center from y) and r ( radius).
Attribute Value
cx Centre from x axis
cy Centre from y axis
r Radius of circle
fill Fill background of Circle
stroke color of outline. ( Default color is black)
stroke-width width of stroke. ( Default width is 1px)
<style>
#cir:hover{ fill:red} // Will change background of svg on hover.
</style>
<svg width="200" height="200" style="border:1px solid #ccc; margin-right:5px">
<circle cx="100" cy="100" r="50" fill="aqua" />
</svg>
<svg width="200" height="200" style="border:1px solid #ccc">
<circle cx="100" cy="100" r="50" fill="silver" stroke="red" stroke-width='3' />
</svg>
<svg width="200" height="200" style="border:1px solid #ccc">
<circle id="cir" cx="100" cy="100" r="50" fill="silver" stroke="blue" stroke-width='3' />
</svg>
OUTPUT
HTML5 − SVG Rectangle
SVG Rect can create rectangle inside an SVG tag. A rectangle can have x (
horizontal distance from left-top corner ), y ( vertical distance from left-top corner ), width
and height. Default fill ( background-color) of rectangle is black.
Attribute Value
x Distance from x axis
y Distance from y axis
width Width of rectangle
height Height of rectangle
fill Fill background of rectangle
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 4 of 10
Computer Animation & Multimedia
stroke color of outline. ( Default color is black)
stroke-width width of stroke. ( Default width is 1px)
<svg width="200" height="200" style="border:1px solid #ccc; margin-right:5px">
<rect x="10" y="10" width="100" height="100" fill="aqua" ></rect>
</svg>
<svg width="200" height="200" style="border:1px solid #ccc">
<rect x="10" y="10" width="150" height="100" fill="#ccc" stroke="red" ></rect>
</svg>
<svg width="200" height="200" style="border:1px solid #ccc">
<rect x="10" y="10" width="150" height="100" fill="#444"
stroke="#0ff" stroke-width="10px" ></rect>
</svg>
OUTPUT
HTML5 − SVG Line
How to create a line in SVG element. A line consist of two points. Thus we need one
x1, one y1, one x2, and one y2. A line can have stroke and stroke-width, but can't be filled
as it is not a shape like rectangle and circle.
SVG Line Attributes
Attribute Value
x1 first point on x axis
y1 first point on y axis
x2 second point on x axis
y2 second point on y axis
stroke color of outline. ( Default color is black)
stroke-width width of stroke. ( Default width is 1px)
Following is the HTML5 version of an SVG example which would draw a line using <line>
tag −
<svg width="200" height="200" style="border:1px solid #ccc">
<line x1="0" y1="0" x2="200" y2="200" stroke="black"> </line>
</svg>
<svg width="200" height="200" style="border:1px solid #ccc">
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 5 of 10
Computer Animation & Multimedia
<line x1="200" y1="0" x2="0" y2="200" stroke="black"> </line>
</svg>
<svg width="200" height="200" style="border:1px solid #ccc">
<line x1="100" y1="0" x2="100" y2="200" stroke="red" stroke-width="5"> </line>
<line x1="0" y1="100" x2="200" y2="100" stroke="blue" stroke-width="3"></line>
</svg>
OUTPUT
You can use the style attribute which allows you to set additional style information like
stroke and fill colors, width of the stroke, etc.
This would produce the following result in HTML5 enabled latest version of Firefox.
HTML5 − SVG Ellipse
SVG ellipse can create ellipse inside an SVG tag.
Attribute Value
rx Radius on x-axis
ry Radius on y-axis
cx Center Position from left
cy Center Position from Top
stroke Outline width
<style>
#svg-3:hover{ fill:aqua} // Will change background of svg on hover.
</style>
<svg width="200" height="200" style="border:1px solid #ccc; ">
<ellipse ry="41" rx="76" id="svg-1" cy="78" cx="121" fill="#F00"/>
</svg>
<svg width="200" height="200" style="border:1px solid #ccc">
<ellipse ry="41" rx="76" id="svg-2" cy="78" cx="121" stroke-width="5"
stroke="#000000" fill="#F00"/>
</svg>
<svg width="200" height="200" style="border:1px solid #ccc">
<ellipse ry="41" rx="76" id="svg-3" cy="78" cx="121" stroke-width="5"
stroke="#000000" fill="#F00"/>
</svg>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 6 of 10
Computer Animation & Multimedia
OUTPUT
HTML5 − SVG Polygon
SVG Polygon is used to build a polygon with minimum 3 sides. A ploygon can be used to
build a triangle, rectangle, square, pentagon, star etc.
SVG Polygon Attributes
Attribute Use
points to set x and y coordinates. See Example
<polygon points="100,100 200,100 200,200 100,200"></polygon>
fill fill background color of polygon
stroke set stroke-color of polygon
stroke-width set stroke-width of polygon
fill-rule evenodd, default is nonzero
SVG Polygon Example
SVG Trapezium
<polygon points="60,20 260,20 300,120 20,120" fill="#fd5f5f" stroke="black"></polygon>
SVG Pentagon
<polygon points="150,20 200,60 180,110 120,110 100,60" fill="aqua"
stroke="black"></polygon>
SVG STAR
<polygon points="150,25 120,110 200,60 100,60 180,110" fill="aqua"
stroke="black"></polygon>
SVG STAR with fillrule evenodd
<polygon points="150,25 120,110 200,60 100,60 180,110" fill="blue" fill-rule="evenodd"
stroke="black"></polygon>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 7 of 10
Computer Animation & Multimedia
OUTPUT
HTML5 − SVG Polyline
Following is the HTML5 version of an SVG example which would draw a polyline using
<polyline> tag −
<!DOCTYPE html>
<html>
<head>
<style>
#svgelem {
position: relative;
left: 50%;
-webkit-transform: translateX(-20%);
-ms-transform: translateX(-20%);
transform: translateX(-20%);
}
</style>
<title>SVG</title>
<meta charset = "utf-8" />
</head>
<body>
<h2 align = "center">HTML5 SVG Polyline</h2>
<svg id = "svgelem" height = "200" xmlns = "http://www.w3.org/2000/svg">
<polyline points = "0,0 0,20 20,20 20,40 40,40 40,60" fill = "red" />
</svg>
</body>
</html>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 8 of 10
Computer Animation & Multimedia
HTML5 − SVG Gradients
Following is the HTML5 version of an SVG example which would draw an ellipse using
<ellipse> tag and would use <radialGradient> tag to define an SVG radial gradient.
Similarly, you can use <linearGradient> tag to create SVG linear gradient.
<!DOCTYPE html>
<html>
<head>
<style>
#svgelem {
position: relative;
left: 50%;
-webkit-transform: translateX(-40%);
-ms-transform: translateX(-40%);
transform: translateX(-40%);
}
</style>
<title>SVG</title>
<meta charset = "utf-8" />
</head>
<body>
<h2 align = "center">HTML5 SVG Gradient Ellipse</h2>
<svg id = "svgelem" height = "200" xmlns = "http://www.w3.org/2000/svg">
<defs>
<radialGradient id="gradient" cx = "50%" cy = "50%" r = "50%" fx = "50%"
fy = "50%">
<stop offset = "0%" style = "stop-color:rgb(200,200,200); stop-opacity:0"/>
<stop offset = "100%" style = "stop-color:rgb(0,0,255); stop-opacity:1"/>
</radialGradient>
</defs>
<ellipse cx = "100" cy = "50" rx = "100" ry = "50"
style = "fill:url(#gradient)" />
</svg>
</body>
</html>
This would produce the following result in HTML5 enabled latest version of Firefox.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 9 of 10
Computer Animation & Multimedia
HTML5 - SVG Animation
To add animation in svg, <animateMotion> tag is used in svg element. Path, dur
and repeatCount are attributes of animateMotion tag.
SVG animateMotion attributes
Attribute Use
path M means moveto, V means vertical, H means horizontal, Z means back to
first frame.
For exp: path="M 0 0 V 10" will move up and down,
For exp: path="M 0 0 V 0 H 10" will move left and right,
dur duration of animation (in s), can be be 1s, 2s or more.
repeatCount can be a number, or indefinite for inifinite times.
SVG Animation Example
<svg>
<g>
<circle cx="250" cy="90" r="10" fill="red"></circle>
<animateMotion path="M 0 0 V 0 H 100 Z" dur="2s" repeatCount="indefinite" />
</g>
</svg>
<svg>
<g>
<circle cx="10" cy="10" r="10" fill="blue"></circle>
<animateMotion path="M 0 0 V 130 H 280 Z" dur="4s" repeatCount="indefinite" />
</g>
</svg>
OUTPUT
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 10 of 10
Computer Animation & Multimedia
UNIT – 4
HTML5 - CANVAS
Introduction to HTML5 - Canvas
HTML5 element <canvas> gives you an easy and powerful way to draw graphics
using JavaScript. It can be used to draw graphs, make photo compositions or do simple (and
not so simple) animations.
Canvas has several methods for drawing paths, boxes, circles, text, and adding
images. The canvas would be a rectangular area on an HTML page. By default, a canvas has
no border and no content.
Syntax:
<canvas>
Content...
</canvas>
It is recommended to have 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.
Supported Properties: The properties like Colors, Styles, Shadows, Line Styles, Rectangles,
Paths, Transformations, Text, Pixel Manipulation, Compositing & Image Drawing, are the
global attributes that are supported by all the canvas tags. Please refer to the HTML Canvas
Complete Reference article for the details.
Here is a simple <canvas> element which has only two specific
attributes width and height plus all the core HTML5 attributes like id, name and class, etc.
<canvas id = "mycanvas" width = "100" height = "100"></canvas>
You can easily find that <canvas> element in the DOM using getElementById() method as
follows −
var canvas = document.getElementById("mycanvas");
Let us see a simple example on using <canvas> element in HTML5 document.
<!DOCTYPE HTML>
<html>
<head>
<style>
#mycanvas{border:1px solid red;}
</style>
</head>
<body>
<canvas id = "mycanvas" width = "100" height = "100"></canvas>
</body>
</html>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 1 of 42
Computer Animation & Multimedia
The Rendering Context
The <canvas> is initially blank, and to display something, a script first needs to access
the rendering context and draw on it.
The canvas element has a DOM method called getContext, used to obtain the rendering
context and its drawing functions. This function takes one parameter, the type of context2d.
Following is the code to get required context along with a check if your browser supports
<canvas> element −
var canvas = document.getElementById("mycanvas");
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
// drawing code here
} else {
// canvas-unsupported code here
}
Browser Support
The latest versions of Firefox, Safari, Chrome and Opera all support for HTML5
Canvas but IE8 does not support canvas natively.
You can use ExplorerCanvas to have canvas support through Internet Explorer. You just
need to include this JavaScript as follows −
<!--[if IE]><script src = "excanvas.js"></script><![endif]-->
HTML5 Canvas Examples
The below table covers the following examples related to HTML5 <canvas> element.
Sr. No. Examples & Description
Drawing Rectangles
1
Learn how to draw rectangle using HTML5 <canvas> element
Drawing Paths
2
Learn how to make shapes using paths in HTML5 <canvas> element
Drawing Lines
3
Learn how to draw lines using HTML5 <canvas> element
Drawing Bezier
4
Learn how to draw Bezier curve using HTML5 <canvas> element
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 2 of 42
Computer Animation & Multimedia
Drawing Quadratic
5
Learn how to draw quadratic curve using HTML5 <canvas> element
Using Images
6
Learn how to use images with HTML5 <canvas> element
Create Gradients
7
Learn how to create gradients using HTML5 <canvas> element
Styles and Colors
8
Learn how to apply styles and colors using HTML5 <canvas> element
Text and Fonts
9
Learn how to draw amazing text using different fonts and their size.
Pattern and Shadow
10
Learn how to draw different patterns and drop shadows.
Canvas States
11 Learn how to save and restore canvas states while doing complex drawings on
a canvas.
Canvas Translation
12 This method is used to move the canvas and its origin to a different point in
the grid.
Canvas Rotation
13
This method is used to rotate the canvas around the current origin.
Canvas Scaling
14
This method is used to increase or decrease the units in a canvas grid.
Canvas Transform
15
These methods allow modifications directly to the transformation matrix.
Canvas Composition
16
This method is used to mask off certain areas or clear sections from the canvas.
Canvas Animation
17
Learn how to create basic animation using HTML5 canvas and JavaScript.
Canvas Drawing Rectangles
There are three methods that draw rectangles on the canvas −
Sr.No. Method and Description
fillRect(x,y,width,height)
1
This method draws a filled rectangle.
strokeRect(x,y,width,height)
2
This method draws a rectangular outline.
clearRect(x,y,width,height)
3
This method clears the specified area and makes it fully transparent
Here x and y specify the position on the canvas (relative to the origin) of the top-left corner
of the rectangle and width and height are width and height of the rectangle.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 3 of 42
Computer Animation & Multimedia
Example
Following is a simple example which makes use of above mentioned methods to draw a
nice rectangle.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// Get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Draw shapes
ctx.fillRect(25,25,100,100);
ctx.clearRect(45,45,60,60);
ctx.strokeRect(50,50,50,50);
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 4 of 42
Computer Animation & Multimedia
Canvas Drawing Paths
We require the following methods to draw paths on the canvas −
S.No. Method and Description
beginPath()
1
This method resets the current path.
moveTo(x, y)
2
This method creates a new subpath with the given point.
closePath()
3 This method marks the current subpath as closed, and starts a new subpath with
a point the same as the start and end of the newly closed subpath.
fill()
4
This method fills the subpaths with the current fill style.
stroke()
5
This method strokes the subpaths with the current stroke style.
arc(x, y, radius, startAngle, endAngle, anticlockwise)
Adds points to the subpath such that the arc described by the circumference of the
6 circle described by the arguments, starting at the given start angle and ending at
the given end angle, going in the given direction, is added to the path, connected
to the previous point by a straight line.
Example
Following is a simple example which makes use of above mentioned methods to draw a
shape.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 5 of 42
Computer Animation & Multimedia
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Draw shapes
ctx.beginPath();
ctx.arc(75,75,50,0,Math.PI*2,true); // Outer circle
ctx.moveTo(110,75);
ctx.arc(75,75,35,0,Math.PI,false); // Mouth
ctx.moveTo(65,65);
ctx.arc(60,65,5,0,Math.PI*2,true); // Left eye
ctx.moveTo(95,65);
ctx.arc(90,65,5,0,Math.PI*2,true); // Right eye
ctx.stroke();
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 6 of 42
Computer Animation & Multimedia
Canvas Line Methods
We require the following methods to draw lines on the canvas −
Sr.No. Method and Description
beginPath()
1
This method resets the current path.
moveTo(x, y)
2
This method creates a new subpath with the given point.
closePath()
3 This method marks the current subpath as closed, and starts a new subpath with
a point the same as the start and end of the newly closed subpath.
fill()
4
This method fills the subpaths with the current fill style.
stroke()
5
This method strokes the subpaths with the current stroke style.
lineTo(x, y)
6 This method adds the given point to the current subpath, connected to the
previous one by a straight line.
Example
Following is a simple example which makes use of the above-mentioned methods to draw
a triangle.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 7 of 42
Computer Animation & Multimedia
// Filled triangle
ctx.beginPath();
ctx.moveTo(25,25);
ctx.lineTo(105,25);
ctx.lineTo(25,105);
ctx.fill();
// Stroked triangle
ctx.beginPath();
ctx.moveTo(125,125);
ctx.lineTo(125,45);
ctx.lineTo(45,125);
ctx.closePath();
ctx.stroke();
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 8 of 42
Computer Animation & Multimedia
Canvas Line Properties
There are several properties which allow us to style lines.
S.No. Property and Description
lineWidth [ = value ]
1 This property returns the current line width and can be set, to change the line
width.
lineCap [ = value ]
2 This property returns the current line cap style and can be set, to change the line
cap style. The possible line cap styles are butt, round, and square
lineJoin [ = value ]
3 This property returns the current line join style and can be set, to change the line
join style. The possible line join styles are bevel, round, andmiter.
miterLimit [ = value ]
4 This property returns the current miter limit ratio and can be set, to change the
miter limit ratio.
Example
Following is a simple example which makes use of lineWidth property to draw lines of
different width.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
for (i=0;i<10;i++){
ctx.lineWidth = 1+i;
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 9 of 42
Computer Animation & Multimedia
ctx.beginPath();
ctx.moveTo(5+i*14,5);
ctx.lineTo(5+i*14,140);
ctx.stroke();
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
Canvas - Drawing Bezier Curves
We need the following methods to draw Bezier curves on the canvas −
S.No. Method and Description
beginPath()
1
This method resets the current path.
moveTo(x, y)
2
This method creates a new subpath with the given point.
closePath()
3 This method marks the current subpath as closed, and starts a new subpath with
a point the same as the start and end of the newly closed subpath.
fill()
4
This method fills the subpaths with the current fill style.
stroke()
5
This method strokes the subpaths with the current stroke style.
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
6 This method adds the given point to the current path, connected to the previous
one by a cubic Bezier curve with the given control points.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 10 of 42
Computer Animation & Multimedia
The x and y parameters in bezierCurveTo() method are the coordinates of the end point.
cp1x and cp1y are the coordinates of the first control point, and cp2x and cp2y are the
coordinates of the second control point.
Example
Following is a simple example which makes use of above mentioned methods to draw a
Bezier curves.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(75,40);
ctx.bezierCurveTo(75,37,70,25,50,25);
ctx.bezierCurveTo(20,25,20,62.5,20,62.5);
ctx.bezierCurveTo(20,80,40,102,75,120);
ctx.bezierCurveTo(110,102,130,80,130,62.5);
ctx.bezierCurveTo(130,62.5,130,25,100,25);
ctx.bezierCurveTo(85,25,75,37,75,40);
ctx.fill();
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 11 of 42
Computer Animation & Multimedia
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
Canvas - Drawing Quadratic Curves
We require the following methods to draw quadratic curves on the canvas −
S.No. Method and Description
beginPath()
1
This method resets the current path.
moveTo(x, y)
2
This method creates a new subpath with the given point.
closePath()
3 This method marks the current subpath as closed, and starts a new subpath with
a point the same as the start and end of the newly closed subpath.
fill()
4
This method fills the subpaths with the current fill style.
stroke()
5
This method strokes the subpaths with the current stroke style.
quadraticCurveTo(cpx, cpy, x, y)
6 This method adds the given point to the current path, connected to the previous
one by a quadratic Bezier curve with the given control point.
The x and y parameters in quadraticCurveTo() method are the coordinates of the end point.
cpx and cpy are the coordinates of the control point.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 12 of 42
Computer Animation & Multimedia
Example
Following is a simple example which makes use of above mentioned methods to draw a
Quadratic curves.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Draw shapes
ctx.beginPath();
ctx.moveTo(75,25);
ctx.quadraticCurveTo(25,25,25,62.5);
ctx.quadraticCurveTo(25,100,50,100);
ctx.quadraticCurveTo(50,120,30,125);
ctx.quadraticCurveTo(60,120,65,100);
ctx.quadraticCurveTo(125,100,125,62.5);
ctx.quadraticCurveTo(125,25,75,25);
ctx.stroke();
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 13 of 42
Computer Animation & Multimedia
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
Canvas - Using Images
Below table would show how to import an external image into a canvas and then how to
draw on that image by using following methods −
Sr.No. Method and Description
beginPath()
1
This method resets the current path.
moveTo(x, y)
2
This method creates a new subpath with the given point.
closePath()
3 This method marks the current subpath as closed, and starts a new subpath with
a point the same as the start and end of the newly closed subpath.
fill()
4
This method fills the subpaths with the current fill style.
stroke()
5
This method strokes the subpaths with the current stroke style.
drawImage(image, dx, dy)
This method draws the given image onto the canvas. Here image is a reference
6
to an image or canvas object. x and y form the coordinate on the target canvas
where our image should be placed.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 14 of 42
Computer Animation & Multimedia
Example
Following is a simple example which makes use of above mentioned methods to import an
image.
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Draw shapes
var img = new Image();
img.src = '/images/backdrop.jpg';
img.onload = function() {
ctx.drawImage(img,0,0);
ctx.beginPath();
ctx.moveTo(30,96);
ctx.lineTo(70,66);
ctx.lineTo(103,76);
ctx.lineTo(170,15);
ctx.stroke();
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 15 of 42
Computer Animation & Multimedia
</body>
</html>
Canvas - Create Gradients
HTML5 canvas allows us to fill and stroke shapes using linear and radial gradients using
the following methods −
Sr.No. Method and Description
addColorStop(offset, color)
This method adds a color stop with the given color to the gradient at the given
1
offset. Here 0.0 is the offset at one end of the gradient, 1.0 is the offset at the other
end.
createLinearGradient(x0, y0, x1, y1)
This method returns a CanvasGradient object that represents a linear gradient
2 that paints along the line given by the coordinates represented by the arguments.
The four arguments represent the starting point (x1,y1) and end point (x2,y2) of
the gradient.
createRadialGradient(x0, y0, r0, x1, y1, r1)
This method returns a CanvasGradient object that represents a radial gradient
3 that paints along the cone given by the circles represented by the arguments. The
first three arguments define a circle with coordinates (x1,y1) and radius r1 and
the second a circle with coordinates (x2,y2) and radius r2.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 16 of 42
Computer Animation & Multimedia
Linear Gradient Example
Following is a simple example which makes use of above mentioned methods to create
Linear gradient.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width:100px;
height:100px;
margin:0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Create Linear Gradients
var lingrad = ctx.createLinearGradient(0,0,0,150);
lingrad.addColorStop(0, '#00ABEB');
lingrad.addColorStop(0.5, '#fff');
lingrad.addColorStop(0.5, '#66CC00');
lingrad.addColorStop(1, '#fff');
var lingrad2 = ctx.createLinearGradient(0,50,0,95);
lingrad2.addColorStop(0.5, '#000');
lingrad2.addColorStop(1, 'rgba(0,0,0,0)');
// assign gradients to fill and stroke styles
ctx.fillStyle = lingrad;
ctx.strokeStyle = lingrad2;
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 17 of 42
Computer Animation & Multimedia
// draw shapes
ctx.fillRect(10,10,130,130);
ctx.strokeRect(50,50,50,50);
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
Radial Gradient Example
Following is a simple example which makes use of the above-mentioned methods to create
Radial gradient.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width:100px;
height:100px;
margin:0px auto;
}
</style>
<script type = "text/javascript">
function drawShape(){
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 18 of 42
Computer Animation & Multimedia
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext){
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Create gradients
var radgrad = ctx.createRadialGradient(45,45,10,52,50,30);
radgrad.addColorStop(0, '#A7D30C');
radgrad.addColorStop(0.9, '#019F62');
radgrad.addColorStop(1, 'rgba(1,159,98,0)');
var radgrad2 = ctx.createRadialGradient(105,105,20,112,120,50);
radgrad2.addColorStop(0, '#FF5F98');
radgrad2.addColorStop(0.75, '#FF0188');
radgrad2.addColorStop(1, 'rgba(255,1,136,0)');
var radgrad3 = ctx.createRadialGradient(95,15,15,102,20,40);
radgrad3.addColorStop(0, '#00C9FF');
radgrad3.addColorStop(0.8, '#00B5E2');
radgrad3.addColorStop(1, 'rgba(0,201,255,0)');
var radgrad4 = ctx.createRadialGradient(0,150,50,0,140,90);
radgrad4.addColorStop(0, '#F4F201');
radgrad4.addColorStop(0.8, '#E4C700');
radgrad4.addColorStop(1, 'rgba(228,199,0,0)');
// draw shapes
ctx.fillStyle = radgrad4;
ctx.fillRect(0,0,150,150);
ctx.fillStyle = radgrad3;
ctx.fillRect(0,0,150,150);
ctx.fillStyle = radgrad2;
ctx.fillRect(0,0,150,150);
ctx.fillStyle = radgrad;
ctx.fillRect(0,0,150,150);
}
else {
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 19 of 42
Computer Animation & Multimedia
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 20 of 42
Computer Animation & Multimedia
UNIT – 5
HTML5 – STYLES AND COLORS
HTML5 canvas provides the following two important properties to apply colors to a shape
Sr.No. Method and Description
1 fillStyle
This attribute represents the color or style to use inside the shapes.
2 strokeStyle
This attribute represents the color or style to use for the lines around shapes.
By default, the stroke and fill color are set to black which is CSS color value #000000.
A fillStyle Example
Following is a simple example which makes use of the above-mentioned fillStyle attribute
to create a nice pattern.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Create a pattern
for (var i = 0;i<7;i++) {
for (var j = 0;j<7;j++) {
ctx.fillStyle = 'rgb(' + Math.floor(255-20.5*i)+ ','+
Math.floor(255 - 42.5*j) + ',255)';
ctx.fillRect( j*25, i* 25, 55, 55 );
}
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 21 of 42
Computer Animation & Multimedia
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
A strokeStyle Example
Following is a simple example which makes use of the above-mentioned fillStyle attribute
to create another nice pattern.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Create a pattern
for (var i = 0;i<10;i++) {
for (var j = 0;j<10;j++) {
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 22 of 42
Computer Animation & Multimedia
ctx.strokeStyle = 'rgb(255,'+ Math.floor(50-2.5*i)+','+
Math.floor(155 - 22.5 * j ) + ')';
ctx.beginPath();
ctx.arc(1.5+j*25, 1.5 + i*25,10,10,Math.PI*5.5, true);
ctx.stroke();
}
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
HTML5 Canvas - Text and Fonts
HTML5 canvas provides capabilities to create text using different font and text
properties listed below −
Sr.No. Property and Description
font [ = value ]
1
This property returns the current font settings and can be set, to change the font.
textAlign [ = value ]
2 This property returns the current text alignment settings and can be set, to change
the alignment. The possible values are start, end, left, right, and center.
textBaseline [ = value ]
This property returns the current baseline alignment settings and can be set, to
3
change the baseline alignment. The possible values are top, hanging, middle ,
alphabetic, ideographic and bottom.
fillText(text, x, y [, maxWidth ] )
4 This property fills the given text at the given position indicated by the given
coordinates x and y.
5 strokeText(text, x, y [, maxWidth ] )
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 23 of 42
Computer Animation & Multimedia
This property strokes the given text at the given position indicated by the given
coordinates x and y.
Example
Following is a simple example which makes use of above mentioned attributes to draw a
text −
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#00F';
ctx.font = 'Italic 30px Sans-Serif';
ctx.textBaseline = 'Top';
ctx.fillText('Hello world!', 40, 100);
ctx.font = 'Bold 30px Sans-Serif';
ctx.strokeText('Hello world!', 40, 50);
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 24 of 42
Computer Animation & Multimedia
HTML5 Canvas - Pattern and Shadow
Create Pattern
There is following method required to create a pattern on the canvas −
Sr.No. Method and Description
createPattern(image, repetition)
This method will use image to create the pattern. The second argument could be
1
a string with one of the following values: repeat, repeat-x, repeaty, andno-repeat.
If the empty string or null is specified, repeat will. be assumed
Example
Following is a simple example which makes use of above mentioned method to create a nice
pattern.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width:100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// create new image object to use as pattern
var img = new Image();
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 25 of 42
Computer Animation & Multimedia
img.src = 'images/pattern.jpg';
img.onload = function() {
// create pattern
var ptrn = ctx.createPattern(img,'repeat');
ctx.fillStyle = ptrn;
ctx.fillRect(0,0,150,150);
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
Create Shadows
HTML5 canvas provides capabilities to create nice shadows around the drawings. All
drawing operations are affected by the four global shadow attributes.
Sr.No. Property and Description
shadowColor [ = value ]
1 This property returns the current shadow color and can be set, to change the
shadow color.
shadowOffsetX [ = value ]
2 This property returns the current shadow offset X and can be set, to change the
shadow offset X.
shadowOffsetY [ = value ]
3 This property returns the current shadow offset Y and can be set, change the
shadow offset Y.
shadowBlur [ = value ]
4 This property returns the current level of blur applied to shadows and can be set,
to change the blur level.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 26 of 42
Computer Animation & Multimedia
Example
Following is a simple example which makes use of above mentioned attributes to draw a
shadow.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
ctx.shadowBlur = 2;
ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
ctx.font = "20px Times New Roman";
ctx.fillStyle = "Black";
ctx.fillText("This is shadow test", 5, 30);
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 27 of 42
Computer Animation & Multimedia
HTML5 Canvas - Save and Restore States
HTML5 canvas provides two important methods to save and restore the canvas states. The
canvas drawing state is basically a snapshot of all the styles and transformations that have
been applied and consists of the followings −
• The transformations such as translate, rotate and scale etc.
• The current clipping region.
• The current values of the following attributes − strokeStyle, fillStyle, globalAlpha,
lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur,
shadowColor, globalCompositeOperation, font, textAlign, textBaseline.
Canvas states are stored on a stack every time the save method is called, and the last saved
state is returned from the stack every time the restore method is called.
Sr.No. Method and Description
save()
1
This method pushes the current state onto the stack..
restore()
2
This method pops the top state on the stack, restoring the context to that state.
Example
Following is a simple example which makes use of above mentioned methods to show how
the restore is called, to restore the original state and the last rectangle is once again drawn in
black.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 28 of 42
Computer Animation & Multimedia
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// draw a rectangle with default settings
ctx.fillRect(0,0,150,150);
// Save the default state
ctx.save();
// Make changes to the settings
ctx.fillStyle = '#66FFFF'
ctx.fillRect( 15,15,120,120);
// Save the current state
ctx.save();
// Make the new changes to the settings
ctx.fillStyle = '#993333'
ctx.globalAlpha = 0.5;
ctx.fillRect(30,30,90,90);
// Restore previous state
ctx.restore();
// Draw a rectangle with restored settings
ctx.fillRect(45,45,60,60);
// Restore original state
ctx.restore();
// Draw a rectangle with restored settings
ctx.fillRect(40,40,90,90);
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 29 of 42
Computer Animation & Multimedia
HTML5 Canvas – Translation
HTML5 canvas provides translate(x, y) method which is used to move the canvas and its
origin to a different point in the grid.
Here argument x is the amount the canvas is moved to the left or right, and y is the amount
it's moved up or down.
Example
Following is a simple example which makes use of above method to draw various
Spirographs −
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width:100px;
height:100px;
margin:0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
ctx.fillRect(0,0,300,300);
for (i = 0;i<3;i++) {
for (j = 0;j<3;j++) {
ctx.save();
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 30 of 42
Computer Animation & Multimedia
ctx.strokeStyle = "#FF0066";
ctx.translate(50+j*100,50+i*100);
drawSpirograph(ctx,10*(j+3)/(j+2),-2*(i+3)/(i+1),10);
ctx.restore();
}
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
function drawSpirograph(ctx,R,r,O) {
var x1 = R-O;
var y1 = 0;
var i = 1;
ctx.beginPath();
ctx.moveTo(x1,y1);
do {
if (i>20000) break;
var x2 = (R+r)*Math.cos(i*Math.PI/72) - (r+O)*Math.cos(((R+r)/r)*(i*Math.PI/72))
var y2 = (R+r)*Math.sin(i*Math.PI/72) - (r+O)*Math.sin(((R+r)/r)*(i*Math.PI/72))
ctx.lineTo(x2,y2);
x1 = x2;
y1 = y2;
i++;
} while (x2 != R-O && y2 != 0 );
ctx.stroke();
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas" width = "400" height = "400"></canvas>
</body>
</html>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 31 of 42
Computer Animation & Multimedia
HTML5 Canvas - Rotation
HTML5 canvas provides rotate(angle) method which is used to rotate the canvas around
the current origin.
This method only takes one parameter and that's the angle the canvas is rotated by. This is
a clockwise rotation measured in radians.
Example
Following is a simple example which we are running two loops where first loop determines
the number of rings, and the second determines the number of dots drawn in each ring.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
ctx.translate(100,100);
for (i = 1; i<7; i++) {
ctx.save();
ctx.fillStyle = 'rgb('+(51*i)+','+(200-51*i)+',0)';
for (j = 0; j < i*6; j++) {
ctx.rotate(Math.PI*2/(i*6));
ctx.beginPath();
ctx.arc(0,i*12.5,5,0,Math.PI*2,true);
ctx.fill();
}
ctx.restore();
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 32 of 42
Computer Animation & Multimedia
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas" width = "400" height = "400"></canvas>
</body>
</html>
HTML5 Canvas - Scaling
HTML5 canvas provides scale(x, y) method which is used to increase or decrease the
units in our canvas grid. This can be used to draw scaled down or enlarged shapes and
bitmaps.
This method takes two parameters where x is the scale factor in the horizontal direction and
y is the scale factor in the vertical direction. Both parameters must be positive numbers.
Values smaller than 1.0 reduce the unit size and values larger than 1.0 increase the unit size.
Setting the scaling factor to precisely 1.0 doesn't affect the unit size.
Example
Following is a simple example which uses spirograph function to draw nine shapes with
different scaling factors.
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 33 of 42
Computer Animation & Multimedia
ctx.strokeStyle = "#fc0";
ctx.lineWidth = 1.5;
ctx.fillRect(0,0,300,300);
// Uniform scaling
ctx.save()
ctx.translate(50,50);
drawSpirograph(ctx,22,6,5);
ctx.translate(100,0);
ctx.scale(0.75,0.75);
drawSpirograph(ctx,22,6,5);
ctx.translate(133.333,0);
ctx.scale(0.75,0.75);
drawSpirograph(ctx,22,6,5);
ctx.restore();
// Non uniform scaling (y direction)
ctx.strokeStyle = "#0cf";
ctx.save()
ctx.translate(50,150);
ctx.scale(1,0.75);
drawSpirograph(ctx,22,6,5);
ctx.translate(100,0);
ctx.scale(1,0.75);
drawSpirograph(ctx,22,6,5);
ctx.translate(100,0);
ctx.scale(1,0.75);
drawSpirograph(ctx,22,6,5);
ctx.restore();
// Non uniform scaling (x direction)
ctx.strokeStyle = "#cf0";
ctx.save()
ctx.translate(50,250);
ctx.scale(0.75,1);
drawSpirograph(ctx,22,6,5);
ctx.translate(133.333,0);
ctx.scale(0.75,1);
drawSpirograph(ctx,22,6,5);
ctx.translate(177.777,0);
ctx.scale(0.75,1);
drawSpirograph(ctx,22,6,5);
ctx.restore();
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 34 of 42
Computer Animation & Multimedia
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
function drawSpirograph(ctx,R,r,O) {
var x1 = R-O;
var y1 = 0;
var i = 1;
ctx.beginPath();
ctx.moveTo(x1,y1);
do {
if (i>20000) break;
var x2 = (R+r)*Math.cos(i*Math.PI/72) - (r+O)*Math.cos(((R+r)/r)*(i*Math.PI/72))
var y2 = (R+r)*Math.sin(i*Math.PI/72) - (r+O)*Math.sin(((R+r)/r)*(i*Math.PI/72))
ctx.lineTo(x2,y2);
x1 = x2;
y1 = y2;
i++;
}
while (x2 != R-O && y2 != 0 );
ctx.stroke();
}
</script>
</head>
<body onload = "drawShape();">
<canvas id = "mycanvas" width = "400" height = "400"></canvas>
</body>
</html>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 35 of 42
Computer Animation & Multimedia
HTML5 Canvas - Transforms
HTML5 canvas provides methods which allow modifications directly to the transformation
matrix. The transformation matrix must initially be the identity transform. It may then be
adjusted using the transformation methods.
Sr.No. Method and Description
transform(m11, m12, m21, m22, dx, dy)
1 This method changes the transformation matrix to apply the matrix given by the
arguments.
setTransform(m11, m12, m21, m22, dx, dy)
2 This method changes the transformation matrix to the matrix given by the
arguments.
The transform(m11, m12, m21, m22, dx, dy) method must multiply the current
transformation matrix with the matrix described by −
m11 m21 dx
m12 m22 dy
0 0 1
The setTransform(m11, m12, m21, m22, dx, dy) method must reset the current transform to the
identity matrix, and then invoke the transform(m11, m12, m21, m22, dx, dy) method with the
same arguments.
Example
Following is a simple example which makes use of transform() and setTransform() methods
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
var sin = Math.sin(Math.PI/6);
var cos = Math.cos(Math.PI/6);
ctx.translate(200, 200);
var c = 0;
for (var i=0; i <= 12; i++) {
c = Math.floor(255 / 12 * i);
ctx.fillStyle = "rgb(" + c + "," + c + "," + c + ")";
ctx.fillRect(0, 0, 100, 100);
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 36 of 42
Computer Animation & Multimedia
ctx.transform(cos, sin, -sin, cos, 0, 0);
}
ctx.setTransform(-1, 0, 0, 1, 200, 200);
ctx.fillStyle = "rgba(100, 100, 255, 0.5)";
ctx.fillRect(50, 50, 100, 100);
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body onload = "drawShape();">
<canvas id = "mycanvas" width = "400" height = "400"></canvas>
</body>
</html>
HTML5 Canvas - Composition
HTML5 canvas provides compositing attribute globalCompositeOperation which affect all
the drawing operations.
We can draw new shapes behind existing shapes and mask off certain areas, clear sections
from the canvas using globalCompositeOperation attribute as shown below in the example.
There are following values which can be set for globalCompositeOperation −
Sr.No. Attribute & Description
1 source-over
This is the default setting and draws new shapes on top of the existing canvas
content.
2 source-in
The new shape is drawn only where both the new shape and the destination
canvas overlap. Everything else is made transparent.
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 37 of 42
Computer Animation & Multimedia
3 source-out
The new shape is drawn where it doesn't overlap the existing canvas content.
4 source-atop
The new shape is only drawn where it overlaps the existing canvas content.
5 lighter
Where both shapes overlap the color is determined by adding color values.
6 xor
Shapes are made transparent where both overlap and drawn normal everywhere
else.
7 destination-over
New shapes are drawn behind the existing canvas content.
8 destination-in
The existing canvas content is kept where both the new shape and existing canvas
content overlap. Everything else is made transparent.
9 destination-out
The existing content is kept where it doesn't overlap the new shape.
10 destination-atop
The existing canvas is only kept where it overlaps the new shape. The new shape
is drawn behind the canvas content.
11 darker
Where both shapes overlap the color is determined by subtracting color values.
Example
Following is a simple example which makes use of globalCompositeOperation attribute to
create all possible compositions −
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
var compositeTypes = [
'source-over','source-in','source-out','source-atop',
'destination-over','destination-in','destination-out',
'destination-atop','lighter','darker','copy','xor'
];
function drawShape() {
for (i=0;i<compositeTypes.length;i++) {
var label = document.createTextNode(compositeTypes[i]);
document.getElementById('lab'+i).appendChild(label);
var ctx = document.getElementById('tut'+i).getContext('2d');
// draw rectangle
ctx.fillStyle = "#FF3366";
ctx.fillRect(15,15,70,70);
// set composite property
ctx.globalCompositeOperation = compositeTypes[i];
// draw circle
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 38 of 42
Computer Animation & Multimedia
ctx.fillStyle = "#0066FF";
ctx.beginPath();
ctx.arc(75,75,35,0,Math.PI*2,true);
ctx.fill();
}
}
</script>
</head>
<body onload = "drawShape();">
<table border = "1" align = "center">
<tr>
<td><canvas id = "tut0" width = "125" height = "125"></canvas><br/>
<label id = "lab0"></label>
</td>
<td><canvas id = "tut1" width = "125" height = "125"></canvas><br/>
<label id = "lab1"></label>
</td>
<td><canvas id = "tut2" width = "125" height = "125"></canvas><br/>
<label id = "lab2"></label>
</td>
</tr>
<tr>
<td><canvas id = "tut3" width = "125" height = "125"></canvas><br/>
<label id = "lab3"></label>
</td>
<td><canvas id = "tut4" width = "125" height = "125"></canvas><br/>
<label id = "lab4"></label>
</td>
<td><canvas id = "tut5" width = "125" height = "125"></canvas><br/>
<label id = "lab5"></label>
</td>
</tr>
<tr>
<td><canvas id = "tut6" width = "125" height = "125"></canvas><br/>
<label id = "lab6"></label>
</td>
<td><canvas id = "tut7" width = "125" height = "125"></canvas><br/>
<label id = "lab7"></label>
</td>
<td><canvas id = "tut8" width = "125" height = "125"></canvas><br/>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 39 of 42
Computer Animation & Multimedia
<label id = "lab8"></label>
</td>
</tr>
<tr>
<td><canvas id = "tut9" width = "125" height = "125"></canvas><br/>
<label id = "lab9"></label>
</td>
<td><canvas id = "tut10" width = "125" height = "125"></canvas><br/>
<label id = "lab10"></label>
</td>
<td><canvas id = "tut11" width = "125" height = "125"></canvas><br/>
<label id = "lab11"></label>
</td>
</tr>
</table>
</body>
</html>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 40 of 42
Computer Animation & Multimedia
HTML5 Canvas - Animations
HTML5 canvas provides necessary methods to draw an image and erase it completely. We
can take Javascript help to simulate good animation over a HTML5 canvas.
Following are the two important Javascript methods which would be used to animate an
image on a canvas −
Sr.No. Method and Description
1 setInterval(callback, time);
This method repeatedly executes the supplied code after a
given timemilliseconds.
2 setTimeout(callback, time);
This method executes the supplied code only once after a
given time milliseconds.
Example
Following is a simple example which would rotate a small image repeatedly −
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
var pattern = new Image();
function animate() {
pattern.src = '/html5/images/pattern.jpg';
setInterval(drawShape, 100);
}
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgba(0,0,0,0.4)';
ctx.strokeStyle = 'rgba(0,153,255,0.4)';
ctx.save();
ctx.translate(150,150);
var time = new Date();
ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + (
(2*Math.PI)/6000)*time.getMilliseconds() );
ctx.translate(0,28.5);
ctx.drawImage(pattern,-3.5,-3.5);
ctx.restore();
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 41 of 42
Computer Animation & Multimedia
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body onload = "animate();">
<canvas id = "mycanvas" width = "400" height = "400"></canvas>
</body>
</html>
From the desk of Mr. Manjunath Balluli, Dept. of CS Page 42 of 42