[go: up one dir, main page]

0% found this document useful (0 votes)
31 views75 pages

CM&a Complete Notes

HTML5 is the latest revision of the HTML standard, introducing new features such as semantic elements, improved forms, and multimedia support without third-party plugins. It includes new tags like <article>, <section>, and <video>, while also removing outdated elements in favor of CSS. HTML5 enhances web development with better user experience and device compatibility, but requires modern browsers and can involve lengthy code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views75 pages

CM&a Complete Notes

HTML5 is the latest revision of the HTML standard, introducing new features such as semantic elements, improved forms, and multimedia support without third-party plugins. It includes new tags like <article>, <section>, and <video>, while also removing outdated elements in favor of CSS. HTML5 enhances web development with better user experience and device compatibility, but requires modern browsers and can involve lengthy code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

UNIT - I

OVERVIEW ON 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.

NEW FEATURES

HTML5 introduces a number of 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.
 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 we can program with
JavaScript.
 Audio & Video − We can embed audio or video on our webpages without resorting to
third-party plugins.
 Geolocation − Now visitors can choose to share their physical location with their web
application.
 Microdata − This lets us to create our own vocabularies beyond HTML5 and extend
our web pages with custom semantics.
 Drag and drop − Drag and drop the items from one location to another location on
the same webpage.

1 Archana D A | Department of Computer Science (UCST)


Removed Elements Use Instead Elements

<acronym> <abbr>

<applet> <object>

<basefont> CSS

<big> CSS

<center> CSS

<dir> <ul>

<font> CSS

<frame>

<frameset>

<noframes>

<isindex>

<strike> CSS, <s> or <del>

<tt> CSS

NEW ADDED ELEMENTS IN HTML 5:

 <article>: The <article> tag is used to represent an article. More specifically, the
content within the <article> tag is independent from the other content of the site (even
though it can be related).

 <aside>: The <aside> tag is used to describe the main object of the web page in a
shorter way like a highlighter. The <aside> tag contains mainly author information,
links, related content and so on.

 <figcaption>: The <figcaption> tag in HTML is used to set a caption to the figure
element in a document.

 <figure>: The <figure> tag in HTML is used to add self-contained content like
illustrations, diagrams, photos or codes listing in a document.

2 Archana D A | Department of Computer Science (UCST)


 <header>: It contains the section heading as well as other content, such as a
navigation links, table of contents, etc.

 <footer>: The <footer> tag in HTML is used to define a footer of HTML document.
This section contains the footer information (author information, copyright
information, carriers etc.). The footer tag is used within body tag.

 <main>: Delineates the main content of the body of a document or web app.

 <mark>: The <mark> tag in HTML is used to define the marked text. It is used to
highlight the part of the text in the paragraph.

 <nav>: The <nav> tag is used to declaring the navigational section in HTML
documents. Websites typically have sections dedicated to navigational links, which
enables user to navigate the site.

 <section>: It demarcates a thematic grouping of content.

 <details>: The <details> tag is used for the content/information which is initially
hidden but could be displayed if the user wishes to see it.

 <summary>: The <summary> tag in HTML is used to define a summary for the
<details> element. When the summary is clicked by the user, the content placed inside
the <details> element becomes visible which was previously hidden. The <summary>
tag was added in HTML 5. The <summary> tag requires both starting and ending tag.

 <time>: The <time> tag is used to display the human-readable data/time. It can also
be used to encode dates and times in a machine-readable form. The main advantage
for users is that they can offer to add birthday reminders or scheduled events in their
calendars and search engines can produce smarter search results.

 <bdi>: The <bdi> tag refers to the Bi-Directional Isolation. It differentiates a text
from other text that may be formatted in different direction. This tag is used when a
user generated text with an unknown direction.

 <wbr>: The <wbr> tag in HTML stands for word break opportunity and is used to
define the position within the text which is treated as a line break by the browser. It is
mostly used when the used word is too long and there are chances that the browser
may break lines at the wrong place for fitting the text.

3 Archana D A | Department of Computer Science (UCST)


 <datalist>: The <datalist> tag is used to provide autocomplete feature in the HTML
files. It can be used with input tag, so that users can easily fill the data in the forms
using select the data.

 <keygen>: The <keygen> tag in HTML is used to specify a key-pair generator field
in a form. The purpose of <keygen> element is to provide a secure way to
authenticate users. When a form is submitted then two keys are generated, private key
and public key. The private key stored locally, and the public key is sent to the server.
The public key is used to generate client certificate to authenticate user in future.

 <output>: The <output> tag in HTML is used to represent the result of a calculation
performed by the client-side script such as JavaScript.

 <progress>: It is used to represent the progress of a task. It also defines how much
work is done and how much is left to download a task. It is not used to represent the
disk space or relevant query.

 <svg>: It is the Scalable Vector Graphics.

 <canvas>: The <canvas> tag in HTML is used to draw graphics on web page using
JavaScript. It can be used to draw paths, boxes, texts, gradient and adding images. By
default, it does not contain border and text.

 <audio>: It defines the music or audio content.

 <embed>: Defines containers for external applications (usually a video player).

 <source>: It defines the sources for <video> and <audio>.

 <track>: It defines the tracks for <video> and <audio>.

 <video>: It defines the video content.

Advantages:

 All browsers supported.

 More device friendly.

 Easy to use and implement.

 HTML 5 in integration with CSS, JavaScript, etc. can help build beautiful websites.

4 Archana D A | Department of Computer Science (UCST)


Disadvantages:

 Long codes have to be written which is time consuming.

 Only modern browsers support it.

HTML Forms
An HTML form is used to collect user input. The user input is most often sent to a server for
processing.

Syntax:

<form>
<!--form elements-->
</form>

Form Elements

The HTML <form> comprises several elements, each serving a unique purpose. For instance,
the <label> element is used to define labels for other <form> elements. The <input> element,
on the other hand, is versatile and can be used to capture various types of input data such as
text, password, email, and more, simply by altering its type attribute. Now, let’s all the list of
HTML Form Elements one by one:

Elements Descriptions
<label> It defines labels for <form> elements.
<input> It is used to get input data from the form in various types such as text,
password, email, etc by changing its type.
<button> It defines a clickable button to control other elements or execute a
functionality.
<select> It is used to create a drop-down list.
<textarea> It is used to get input long text content.
<fieldset> It is used to draw a box around other form elements and group the related data.
<legend> It defines a caption for fieldset elements
<datalist> It is used to specify pre-defined list options for input controls.
<output> It displays the output of performed calculations.
<option> It is used to define options in a drop-down list.
<optgroup> It is used to define group-related options in a drop-down list.

5 Archana D A | Department of Computer Science (UCST)


Commonly Used Input Types in HTML Forms

In HTML forms, various input types are used to collect different types of data from users.
Here are some commonly used input types:

<input type=”text”>

Input Type Description


<input type=”text“> Defines a one-line text input field
<input type=”password“> Defines a password field
<input type=”submit“> Defines a submit button
<input type=”reset“> Defines a reset button
<input type=”radio“> Defines a radio button
<input type=”email“> Validates that the input is a valid email address.
<input type=”number“> Allows the user to enter a number. You can specify min, max,
and step attributes for range.
<input type=”checkbox“> Used for checkboxes where the user can select multiple options.
<input type=”date“> Allows the user to select a date from a calendar.
<input type=”time“> Allows the user to select a time.
<input type=”file“> Allows the user to select a file to upload.

Here are some of the key attributes that can be used with the <form> element:

1. action: This attribute specifies where to send the form-data when a form is submitted.
The value of this attribute is typically a URL.

2. method: This attribute defines the HTTP method used to send the form-data. The
values can be “get” or “post”.

3. target: This attribute specifies where to display the response received after submitting
the form. The values can be “_blank”, “_self”, “_parent”, “_top”, or the name of an
iframe.

4. enctype: This attribute is used when method=“post”. It specifies how the form-data
should be encoded when submitting it to the server. The values can be “application/x-
www-form-urlencoded”, “multipart/form-data”, or “text/plain”.

5. autocomplete: This attribute specifies whether a form should have autocomplete on or


off. When autocomplete is on, the browser automatically completes values based on
values that the user has entered before.
6 Archana D A | Department of Computer Science (UCST)
6. novalidate: This Boolean attribute specifies that the form-data should not be validated
on submission.

Radio Button Control


 The radio button is used to select one option from multiple options. It is used for
selection of gender, quiz questions etc.
 If you use one name for all the radio buttons, only one radio button can be selected at
a time.
 Using radio buttons for multiple options, we can only choose a single option at a time.

Checkbox Control

The checkbox control is used to check multiple options from given checkboxes.

Submit button control

HTML <input type="submit"> are used to add a submit button on web page. When user
clicks on submit button, then form get submit to the server.

HTML <textarea> tag in form

The <textarea> tag in HTML is used to insert multiple-line text in a form. The size of
<textarea> can be specify either using "rows" or "cols" attribute or by CSS.

HTML TABLE TAGS

HTML tables allow web developers to arrange data into rows and columns.

Tag Description

<table> Defines a table

<th> Defines a header cell in a table

<tr> Defines a row in a table

<td> Defines a cell in a table

<caption> Defines a table caption

<colgroup> Specifies a group of one or more columns in a table for formatting

7 Archana D A | Department of Computer Science (UCST)


<col> Specifies column properties for each column within a <colgroup> element

<thead> Groups the header content in a table

<tbody> Groups the body content in a table

<tfoot> Groups the footer content in a table

HTML LISTS

HTML lists allow web developers to group a set of related items in lists.

Tag Description

<ul> Defines an unordered list in which items are marked with bullets. It is also
known as bulleted lists. An unordered list starts with the <ul> tag. Each list
item starts with the <li> tag.

<ul type="disc | circle | square">

<ol> Defines an ordered list in which all list items are marked with numbers by
default. An ordered list starts with the <ol> tag. Each list item starts with
the “li” tag.

<ol type="1 | a | A | i | I" start= “number”>

Start specifies from where has numbering has to be start and type specifies
way of numbering.

<li> Defines a list item

<dl> Defines a description list in which a list of terms with a description of each
term. The <dl> tag defines the description list, the <dt> tag defines the term
name, and the <dd> tag describes each term.

<dt> Defines a term in a description list

<dd> Describes the term in a description list

8 Archana D A | Department of Computer Science (UCST)


HTML Images
The HTML <img> tag is used to embed an image in a web page. Images are not technically
inserted into a web page; images are linked to web pages. The <img> tag creates a holding
space for the referenced image.

The <img> tag is empty, it contains attributes only, and does not have a closing tag.

The <img> tag has two required attributes:

 src - Specifies the path to the image

 alt - Specifies an alternate text for the image

Syntax

<img src="url" alt="alternatetext" width= “100” height= “100”>

HTML | <frame> Tag


HTML Frames are a powerful tool for dividing your web browser window into
multiple sections, each capable of loading content independently. This is achieved using a
collection of frames within a frameset tag.

To make frames on a page we use <frameset> tag instead of <body>


tag. The <frameset> tag defines how to divide the window into frames. The rows attribute
of <frameset> tag defines horizontal frames and cols attribute defines vertical frames. Each
frame is indicated by <frame> tag and it defines which HTML document shall open into the
frame.

Attributes of frameset Tag

ATTRIBUTES DESCRIPTION

Specifies how many columns are contained in the frameset and


the size of each column. You can specify the width of each
column in one of four ways.

 Absolute values in pixels. For example to create three


vertical frames, use cols="100, 500,100".

cols  A percentage of the browser window. For example to


create three vertical frames, use cols="10%, 80%,10%".

 Using a wildcard symbol. For example to create three


vertical frames, use cols="10%, *,10%". In this case
wildcard takes remainder of the window.

 As relative widths of the browser window. For example to


create three vertical frames, use cols="3*,2*,1*". This is

9 Archana D A | Department of Computer Science (UCST)


an alternative to percentages. You can use relative widths
of the browser window. Here the window is divided into
sixths: the first column takes up half of the window, the
second takes one third, and the third takes one sixth.

This attribute works just like the cols attribute and takes the same
values, but it is used to specify the rows in the frameset. For
rows example to create two horizontal frames, use rows="10%, 90%".
You can specify the height of each row in the same way as
explained above for columns.

This attribute specifies the width of the border of each frame in


border pixels. For example border="5". A value of zero means no
border.

HTML <frame> Tag Attributes

ATTRIBUTE DESCRIPTION

This attribute is used to give the file name that should be loaded
in the frame. Its value can be any URL. For example,
src
src="/html/top_frame.htm" will load an HTML file available in
html directory.

This attribute allows you to give a name to a frame. It is used to


indicate which frame a document should be loaded into. This is
name especially important when you want to create links in one frame
that load pages into an another frame, in which case the second
frame needs a name to identify itself as the target of the link.

DISADVANTAGES OF FRAMES

 Some smaller devices cannot cope with frames often because their screen is not big
enough to be divided up.

 Sometimes your page will be displayed differently on different computers due to


different screen resolution.

 The browser's back button might not work as the user hopes.

 There are still few browsers that do not support frame technology.

10 Archana D A | Department of Computer Science (UCST)


CASCADING STYLE SHEETS (CSS)

 CSS is the language we use to style a Web page.


 CSS stands for Cascading Style Sheets
 CSS describes how HTML elements are to be displayed on screen, paper, or in other
media
 CSS saves a lot of work. It can control the layout of multiple web pages all at once
 External stylesheets are stored in CSS files

The following are the advantages of CSS −

 CSS saves time − we can write CSS once and then reuse the same sheet in multiple
HTML pages. We can define a style for each HTML element and apply it to as many
Web pages as you want.
 Easy maintenance − To make a global change, simply change the style, and all
elements in all the web pages will be updated automatically.
 Global web standards − Now HTML attributes are being deprecated and it is being
recommended to use CSS. So it's a good idea to start using CSS in all the HTML
pages to make them compatible with future browsers.
 Platform Independence − The Script offer consistent platform independence and can
support latest browsers as well.
CSS Syntax

A CSS rule consists of a selector and a declaration block.

 The selector points to the HTML element you want to style.


 The declaration block contains one or more declarations separated by semicolons.
 Each declaration includes a CSS property name and a value, separated by a colon.
 Multiple CSS declarations are separated with semicolons, and declaration blocks are
surrounded by curly braces.

11 Archana D A | Department of Computer Science (UCST)


LEVELS OF STYLESHEETS

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

1. 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.

Ex: <p style="color:#009900; font-size:50px; font-style:italic; text-align:center;">

CSS makes everything colorful

</p>

2. 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.

<head>
<style>
body {
background-color:powderblue;
}
</style>
</head>

3. 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.

12 Archana D A | Department of Computer Science (UCST)


<link rel="stylesheet" href="stylesheets.css" />

 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.

PRIORITIES OF CSS
 As Inline has the highest priority, any styles that are defined in the internal and external
style sheets are overridden by Inline styles.
 Internal or Embedded stands second in the priority list and overrides the styles in the
external style sheet.
 External style sheets have the least priority. If there are no styles defined either in inline
or internal style sheet then external style sheet rules are applied for the HTML tags.
CSS BASIC PROPERTIES

TEXT PROPERTIES
Property Description Values

color Sets the color of a text RGB, hex, keyword

line-height Sets the distance between lines normal, number, length, %

Increase or decrease the space between


letter-spacing normal, length
characters

text-align Aligns the text in an element left, right, center, justify

text- none, underline, overline, line-


Adds decoration to text
decoration through

Indents the first line of text in an


text-indent length, %
element

text- none, capitalize, uppercase,


Controls the letters in an element
transform lowercase

13 Archana D A | Department of Computer Science (UCST)


LIST PROPERTIES
Property Description Values

Sets all the properties for a list-style-type, list-style-position, list-style-


list-style
list in one declaration image, inherit

list-style- Specifies an image as the


URL, none, inherit
image list-item marker

list-style- Specifies where to place


inside, outside, inherit
position the list-item marker

none, disc, circle, square, decimal, decimal-


leading-zero,
list-style- Specifies the type of list- armenian, georgian, lower-alpha, upper-alpha,
type item marker lower-greek,
lower-latin, upper-latin, lower-roman, upper-
roman, inherit

BORDER PROPERTIES
Property Description Values

Sets all the border


border properties in one border-width, border-style, border-color
declaration

Sets all the bottom border


border-bottom-width, border-bottom-style,
border-bottom properties in one
border-bottom-color
declaration

border-bottom- Sets the color of the bottom


border-color
color border

border-bottom- Sets the style of the bottom


border-style
style border

border-bottom- Sets the width of the


border-width
width bottom border

Sets the color of the four color_name, hex_number,


border-color
borders rgb_number, transparent, inherit

border-left Sets all the left border


border-left-width, border-left-style, border-
properties in one

14 Archana D A | Department of Computer Science (UCST)


declaration left-color

border-left- Sets the color of the left


border-color
color border

border-left- Sets the style of the left


border-style
style border

border-left- Sets the width of the left


border-width
width border

Sets all the right border


border-right-width, border-right-style,
border-right properties in one
border-right-color
declaration

border-right- Sets the color of the right


border-color
color border

border-right- Sets the style of the right


border-style
style border

border-right- Sets the width of the right


border-width
width border

Sets the style of the four none, hidden, dotted, dashed, solid, double,
border-style
borders groove, ridge, inset, outset, inherit

Sets all the top border


border-top-width, border-top-style, border-
border-top properties in one
top-color
declaration

border-top- Sets the color of the top


border-color
color border

border-top- Sets the style of the top


border-style
style border

border-top- Sets the width of the top


border-width
width border

Sets the width of the four


border-width thin, medium, thick, length, inherit
borders

15 Archana D A | Department of Computer Science (UCST)


FONT PROPERTIES
Property Description Values

font-style, font-variant, font-weight, font-


Sets all the font properties size/line-height, font-family, caption, icon,
font
in one declaration menu, message-box, small-caption, status-bar,
inherit

Specifies the font family for


font-family family-name, generic-family, inherit
text

Specifies the font size of xx-small, x-small, small, medium, large, x-large,
font-size
text xx-large, smaller, larger, length, %, inherit

Specifies the font style for


font-style normal, italic, oblique, inherit
text

Specifies whether or not a


font-
text should be displayed in normal, small-caps, inherit
variant
a small-caps font

normal, bold, bolder, lighter,


Specifies the weight of a
font-weight 100, 200, 300, 400, 500, 600, 700, 800, 900,
font
inherit

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

1) CSS ELEMENT SELECTOR

The element selector selects the HTML element by name.

16 Archana D A | Department of Computer Science (UCST)


Ex:
<head>
<style>
p{
text-align: center;
color: blue;
}
</style>
</head>
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.

Ex:
<head>
<style>
#para1 {
text-align: center;
color: blue;
}
</style>
</head>

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.

Ex:
<head>
<style>
.center {
text-align: center; color: blue;
}
</style>

4) CSS Universal Selector

The universal selector is used as a wildcard character. It selects all the elements on the pages.

Ex:
<head>
<style>
*{
color: green; font-size: 20px;
17 Archana D A | Department of Computer Science (UCST)
}
</style>
</head>

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;
}
p{
text-align: center;
color: blue;
}
It can be grouped in following ways:

h1,p {
text-align: center;
color: blue;
}
OVERVIEW ON CSS3

A significant change in CSS3 compared to CSS2 is the introduction of modules. This


functionality has the advantage of expediting the finalization and acceptance of
specifications, as segments can be finalized and accepted incrementally. Also, this allows the
browser to support segments of the specification.

Some of the key modules of CSS3 are:

 Box model

 Image values and replaced content

 Text effects

 Selectors

 Backgrounds and borders

 Animations

 User interface (UI)


18 Archana D A | Department of Computer Science (UCST)
 Multiple column layouts

 2D/3D transformations

ADVANTAGES OF CSS3

 CSS3 provides a consistent and precise positioning of navigable elements.


 It is easy to customize a web page as it can be done by merely altering a modular file.
 Graphics are more accessible in CSS3, thus making it easy to make the site appealing.
 It permits online videos to be seen without using third-party plugins.
 CSS3 is economical and time-saving, and most browsers support it.

DIFFERENCE BETWEEN <SPAN> AND <DIV> TAG

19 Archana D A | Department of Computer Science (UCST)


JAVASCRIPT

JavaScript is a dynamic computer programming language. It is lightweight and most


commonly used as a part of web pages, whose implementations allow client-side script to
interact with the user and make dynamic pages. It is an interpreted programming language
with object-oriented capabilities.

JavaScript was first known as LiveScript, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java. JavaScript made its
first appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core
of the language has been embedded in Netscape, Internet Explorer, and other web browsers.

ADVANTAGES OF JAVASCRIPT

 Less server interaction − We can validate user input before sending the page off to
the server. This saves server traffic, which means less load on our server.

 Immediate feedback to the visitors − We don't have to wait for a page reload to see
if we have forgotten to enter something.

 Increased interactivity − We can create interfaces that react when the user hovers
over them with a mouse or activates them via the keyboard.

 Richer interfaces − We can use JavaScript to include such items as drag-and-drop


components and sliders to give a Rich Interface to your site visitors.

 JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.
 We can place the <script> tags, containing your JavaScript, anywhere within your
web page, but it is normally recommended that you should keep it within
the <head> tags.
 The <script> tag alerts the browser program to start interpreting all the text between
these tags as a script. A simple syntax of your JavaScript will appear as follows.

Ex: <script ...>


JavaScript code
</script>

The script tag takes two important attributes −

20 Archana D A | Department of Computer Science (UCST)


 Language − This attribute specifies what scripting language we are using. Typically,
its value will be javascript. Although recent versions of HTML (and XHTML, its
successor) have phased out the use of this attribute.
 Type − This attribute is what is now recommended to indicate the scripting language
in use and its value should be set to "text/javascript".

So our JavaScript segment will look like −

<script language = "javascript" type = "text/javascript">


JavaScript code
</script>
PRIMITIVE AND NON-PRIMITIVE DATA-TYPES IN JAVASCRIPT

Every Variable has a data type that tells what kind of data is being stored in a variable. There
are two types of data types in JavaScript.

 Primitive data types

 Non-primitive data types

Primitive data types: The predefined data types provided by JavaScript language are known
as primitive data types. Primitive data types are also known as in-built data types.

Below is a list of Primitive Data Types with proper descriptions and examples:

1. Number: Number data type in javascript can be used to hold decimal values as well as
values without decimals.

2. String: The string data type in javascript represents a sequence of characters that are
surrounded by single or double quotes.

3. Undefined: The meaning of undefined is ‘value is not assigned’.

4. Boolean: The boolean data type can accept only two values i.e. true and false.

5. Null: This data type can hold only one possible value that is null.

6. BigInt: This data type can represent numbers greater than 253-1 which helps to perform
operations on large numbers. The number is specified by writing ‘n’ at the end of the value.

7. Symbol: This data type is used to create objects which will always be unique. These
objects can be created using Symbol constructor.

21 Archana D A | Department of Computer Science (UCST)


NON-PRIMITIVE DATA TYPES: The data types that are derived from primitive data
types of the JavaScript language are known as non-primitive data types. It is also known as
derived data types or reference data types.

Non-primitive Data Types

1. Object
2. Array

JAVASCRIPT OPERATORS

JavaScript operators are symbols that are used to perform operations on operands. There are
following types of operators in JavaScript.

1. JAVASCRIPT ARITHMETIC OPERATORS

Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.

Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9

22 Archana D A | Department of Computer Science (UCST)


2. JAVASCRIPT COMPARISON OPERATORS

The JavaScript comparison operator compares the two operands.

Operator Description Example

== Is equal to 10==20 = false

=== Identical (equal and of same type) 10==20 = false

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false

3. JAVASCRIPT BITWISE OPERATORS

The bitwise operators perform bitwise operations on operands.

Operator Description Example

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with Zero (10>>>2) = 2

23 Archana D A | Department of Computer Science (UCST)


4. JAVASCRIPT LOGICAL OPERATORS

Operator Description Example

&& Logical AND (10==20 && 20==33) = false

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true

5. JAVASCRIPT ASSIGNMENT OPERATORS

Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30

-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

6. JAVASCRIPT SPECIAL OPERATORS

Operator Description

(?:) Conditional Operator returns value based on the condition. It is like if-
else.

, Comma Operator allows multiple expressions to be evaluated as single


statement.

delete Delete Operator deletes a property from the object.

in In Operator checks if object has the given property

instanceof checks if the object is an instance of given type

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the generator's iterator.

24 Archana D A | Department of Computer Science (UCST)


KEYBOARD INPUT AND SCREEN OUTPUT
Every web page resides inside a browser window which can be considered as an
object. An object of window is created automatically by the browser. A document object
represents HTML document. The model for the browser display window is the Window
object. It represents the browser window. The Window object has two properties, document
and window, which refer to the Document and Window objects, respectively. The Document
object has several methods and properties. One method is write, which is used to create
output. The parameter is a string, often catenated from parts, some of which are variables

e.g.,document.write("Answer:"+result+"");

JAVASCRIPT DISPLAY POSSIBILITIES

JavaScript can "display" data in different ways:

1) Writing into an HTML element, using innerHTML.


2) Writing into the HTML output using document.write().
3) Writing into an alert box, using window.alert().
4) Writing into the browser console, using console.log().

1) Using innerHTML

• To access an HTML element use document.getElementById(id)

• The id attribute defines the HTML element. The innerHTML property defines the HTML
content:

<!DOCTYPE html>
<html><body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo">
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</p>
</body>
</html>

25 Archana D A | Department of Computer Science (UCST)


2) Using document.write() : document.write() for writing

Example
<!DOCTYPE html>
<html><body>
<h1>My First Web Page</h1>
<p>My first paragraph</p>
<script type = “text/javascript” >
document.write(5 + 6);
</script>
</body>
</html>

3) Using Windows.alert()

 The Window object has three methods for creating dialog boxes for user interactions,
alert, confirm, and prompt.
 The alert method opens a dialog window and displays its parameter in that window. It
also displays an OK button alert(“The sum is :” +sum + “\n”);
 The confirm method opens a dialog window in which the method displays its string
parameter along with two buttons OK and Cancel to offer the user the choice of
continuing some process.

Var question = confirm (“Do you want to continue this download”);

 The prompt method used to create dialog window that contains a textbox used to
collect string of input from the user .The window also includes 2 buttons: OK and
Cancel.
 The prompt takes 2 parameters: the string that prompts user for input and a default
string in case user does not type a string before pressing one of the 2 buttons.

name = prompt(“What is your name?” ,””);

i. alert
Parameter in alert is plain text, not HTML. Opens a dialog box which displays the
parameter string and an OK button.

<!DOCTYPE html>
<html lang =“en”>
<head><title>hi.html</title>
<meta charset = “utf-8” />
<body>
<h1>My First Web Page</h1>
<p>My first paragraph</p>
26 Archana D A | Department of Computer Science (UCST)
<script>
window.alert(5 + 6);
</script>
</body>
</html>

OUTPUT

My First Web Page

My first paragraph

ii. Confirm

Opens a dialog box and displays the parameter and two buttons, OK and Cancel

if (confirm("Press a button!"))
{

txt = "You pressed OK!";


} else {
txt = "You pressed Cancel!";
} window.alert(txt);
iii. Prompt

 Opens a dialog box and displays its string parameter, along with a text box and two
buttons, OK and Cancel.
 The second parameter is for a default response if the user presses OK without typing a
response in the text box

(waits for OK) .

var person = prompt("Please enter your name", "");


if (person == null || person == "") {
txt = "User cancelled the prompt.";
} else {
txt = "Hello " + person + "! How are you?";
}
window.alert(txt);

27 Archana D A | Department of Computer Science (UCST)


UNIT- 2
ANIMATION
ANIMATION

An animation is nothing more than a visualization of change-a change


that occurs over a period of time. An animation lets an element gradually
change from one style to another. We can change as many CSS properties we
want, as many times as we want.

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.

We start off with a small blue circle which was located to the left of the
screen. At the end state, your blue circle now looks sort a kind like below figure.

28 Archana D A | Department of Computer Science (UCST)


Based on inference what changes happened to our blue circle at start and an

end state, one change is the position. Our blue circle starts off on the left side of the

screen. It ends up on the right 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 we would see is a circle that just bounces from left to

right very awkwardly. That is pretty 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, we have two discrete states in time: the start state and the end

state. If we were to play this back, it 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. The process of creating these intermediate states is known as

interpolation.

This interpolation, which occurs over a period of time that we specify, would

look similar to below figure.

Animations can be created in three different ways, they are:

1. CSS animation

2. CSS transition

3. Scripted animation

29 Archana D A | Department of Computer Science (UCST)


1. CSS animations
CSS animations are like traditional animations on some sort of performance-

enhancing substance that makes them more awesome. With these kinds of animations,

we can define not only the beginning and the end state but also any intermediate

states, lovingly known as keyframes.

These intermediate states, if we choose to use them, give us greater control over

the thing you are animating. In Figure 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 we wouldn't see if we simply interpolated between the start

and end states.

Remember, even though we are specifying the intermediate states, our 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 we only define the start

state, end state, and duration. The rest, such as interpolating between the two

states, is taken care of automatically for us.

30 Archana D A | Department of Computer Science (UCST)


3. Scripted/JavaScript animations

If we want full control over what our animation does right down to

how it interpolates between states, we can use JavaScript.

THERE ARE 3 MAJOR PROPERTIES WHICH MAKES ANIMATION TO TAKES PLACE ON WEB

PAGE. THEY ARE:

1. Transformation
2. Transition
3. Keyframes

1. CSS TRANSFORMS
These are a collection of functions that allow to shape elements in particular ways:

• translate: moves the element along up to 3 axis (x, y and z)

• rotate: moves the element around a central point

• scale: resizes the element

• skew: distorts the element

Transform properties

There are 3 CSS transform properties available:

• defines which transform function to use (translate, rotate, scale...)


• allows to modify the origin point of a transformation (works
like background positions)

• is for 3d settings

31 Archana D A | Department of Computer Science (UCST)


a) TRANSLATE
The translate() function allows to move an element across the plane (on the x and y

axis). It accepts either:

• 1 parameter: moves the element along the x axis

• 2 parameters: first value is for the x axis, second for they axis.

translate(x, y) Defines a 2D translation

translate3d(x,y,z) Defines a 3D translation

translateX(x) Defines a translation, using only the value for the X-axis

translateY(y) Defines a translation, using only the value for the Y-axis

translateZ(z) Defines a 3D translation, using only the value for the Z-axis

Example:

@keyframes translating {
0% {transform: translate(0%, 0%);}

25% {transform: translate(20%, 0%);}


75% {transform: translate(0%, 40%);}
100%{ transform: translate(0%, 0%);}

p{ animation: translating 2s ease-out infinite;}

b) ROTATE
The rotate() function allows to make an element revolve around a fixed point. By

default, it revolves around the element's centre. rotate() accepts only 1 parameter,

which is an angle value defined in degrees (deg), gradians (grad), radians (rad) or

turns turn (with 1 turn being equivalent to a full circle).

32 Archana D A | Department of Computer Science (UCST)


rotate(angle) Defines a 2D rotation, the angle is specified in the
parameter

rotate3d(x,y,z,angle) Defines a 3D rotation

rotateX(angle) Defines a 3D rotation along the X-axis

rotateY(angle) Defines a 3D rotation along the Y-axis

rotateZ(angle) Defines a 3D rotation along the Z-axis

Example:

@keyframes rotate {
0% {transform: rotate(0deg);}

100%{ transform:

rotate(180deg);}

p{ animation: rotate 2s linear infinite;}

c) SCALE

The scale() function allows to resize an element. It can either expand or shrink it. The
function accepts either:

• 1 parameter: the element is resized uniformly in height and width

• 2 parameters: the first value resizes the element horizontally, the second
one vertically

The range of possible value is:

• 1: the element retains its original size

• 2: the element doubles in size

• 0.5: the element is half of its size

• 0: the element basically disappears (as its height and width are equal to zero)

• -1: the element is mirrored

33 Archana D A | Department of Computer Science (UCST)


scale(x,y) Defines a 2D scale transformation

scale3d(x,y,z) Defines a 3D scale transformation

scaleX(x) Defines a scale transformation by giving a value for the X-axis

scaleY(y) Defines a scale transformation by giving a value for the Y-axis

scaleZ(z) Defines a 3D scale transformation by giving a value for the Z-


axis
Example:

@keyframes scale {
0% {transform: scale(1);}

20% { transform: scale(2);}

40% {transform: scale(0.5);}


60% {transform: scale(0);}

80% {transform: scale(-1);}


100% {transform: scale(1);}
}

p{ animation: scale 10s steps(1) 0s infinite;}

d) SKEW

The skew() function allows to distort an element, by dragging its sides along a line

basically. This transform function is rarely used, as its effects are quite

unpredictable, and its results not necessarily appealing. Like scale(), the skew()

functions accepts either:

• 1 parameter: the element is distorted horizontally

• 2 parameters: the first value distorts the element horizontally, the

second one vertically And like rotate(), skew() only accepts angle values like
34 Archana D A | Department of Computer Science (UCST)
degrees deg.

skew(x-angle, y- angle) Defines a 2D skew transformation along the X-


and the axis

skewX(angle) Defines a 2D skew transformation along the X-


axis

skewY( angle) Defines a 2D skew transformation along the Y-


axis

Example:

@keyframes skew {
0% { transform: skew(0deg);}
20% { transform: skew(10deg);}
40% { transform: skew(45deg);}

60% { transform: skew(90deg);}


80% { transform:
skew(120deg);}
100%{ transform: skew(0deg);}
}

p{ animation: skew 10s steps(1) 0s infinite;}

2. CSS TRANSITION

CSS transitions provide a way to control animation speed when changing CSS

properties. Instead of having property changes take effect immediately, we can cause

the changes in a property to take place over a period of time.

CSS Transitions can be controlled through shorthand transition property. This is the

best way to configure transitions, as it makes it easier to avoid out of sync

parameters, which can be very frustrating to have to spend lots of time debugging in

CSS. We can control the individual components of the transition with the following

sub-properties:

35 Archana D A | Department of Computer Science (UCST)


a) Transition-property

Specifies the name or names of the CSS properties to which transitions should

be applied. Only properties listed here are animated during transitions; changes to

all other properties occur instantaneously as usual.

b) Transition-duration

Specifies the duration over which transitions should occur. You can specify a

single duration that applies to all properties during the transition, or multiple values

to allow each property to transition over a different period of time.

c) Transition-timing-function

Specifies a function to define how intermediate values for properties are

computed. Timing functions determine how intermediate values of the transition are

calculated. Most timing functions can be specified by providing the graph of the

corresponding function, as defined by four points defining a cubic Bezier.

The transition-timing-function property can have the following values:

• ease - specifies a transition effect with a slow start, then fast, then end slowly (this is

default)

• linear - specifies a transition effect with the same speed from start to end

• ease-in - specifies a transition effect with a slow start

• ease-out - specifies a transition effect with a slow end

• ease-in-out - specifies a transition effect with a slow start and end

• cubic-bezier(n,n,n,n) - lets you define your own values in a cubic-bezier function

d) Transition-delay

Defines how long to wait between the time a property is changed and the transition

actually begins.

36 Archana D A | Department of Computer Science (UCST)


The shorthand transition CSS syntax represented as follows:

div { transition: <property> <duration> <timing-function> <delay>;}

EXAMPLE

This code changes the font family of text in 6seconds with a 3s time delay

between the time the user mouses hover the element to the beginning of the

animation effect:

#delay {

font-family: Arial, Helvetica,


sans-serif; transition-property:
font-size; transition-duration:
4s;
transition-delay: 2s;
}

#delay:hover {
font-family: "Lucida Console", "Courier New", monospace;
}

MULTIPLE TRANSITION PROPERTIES EXAMPLE

.box {
border-style:
double;
border-width:
5px;
display: block;
width:
80px;
height:
75px;
background-color: black;
transition: width 2s, height 2s, background-color 2s, rotate 2s;
}
.box:hover {
background-color: indigo;
width: 125px;
height: 160px;
rotate: 120deg;
}

37 Archana D A | Department of Computer Science (UCST)


Transition + Transformation

<!DOCTYPE html>
<html>
<head>
<title>Transition + Transform</title>
<style>
div {
width: S0px;
height: S0px;
background: purple;
transition: width 5s, height 3s, transform 4s;
}

div:hover
{
width: 150px;
height: 120px;
transform: rotate(360deg);
}

</style>
</head>
<body>
<div></div>
</body>
</html>

3. KEYFRAMES

The @keyframes CSS at-rule controls the intermediate steps in a CSS animation

sequence by defining styles for keyframes (or waypoints) along the animation

sequence. This gives more control over the intermediate steps of the animation

sequence than transitions.

To use keyframes, create a @keyframes rule with a name that is then used by

the animation-name property to match an animation to its keyframe declaration.

Each @keyframes rule contains a style list of keyframe selectors, which specify

percentages along the animation when the keyframe occurs, and a block containing

the styles for that keyframe.

38 Archana D A | Department of Computer Science (UCST)


Syntax:

@keyframes animation-name {keyframes-selector {css-styles;}}

• animation-name: The animation-name is required and it defines the

animation name.

• keyframes-selector: The keyframes-selector defines the percentage of the

animation. It lies between 0% to 100%. One animation can contain many

selectors.

• css-styles: The css-styles defines the one or more legal or applicable CSS style

properties.

ANIMATION PROPERTIES

CSS Syntax

animation: <name> <duration> <timing-function> <delay> <iteration-count> <direction>

<fill-mode> <play-state>;

PROPERTY VALUES

VALUE DESCRIPTION

animation- name Specifies the name of the keyframe we want to bind to the
selector
Specifies how many seconds or milliseconds an animation takes
animation- duration
to complete

Ease
Specifies the
animation- timing- Linear
speed curve of the Ease-in
function Ease-out
animation
Ease-in-out

animation- delay Specifies a delay before the animation will start

39 Archana D A | Department of Computer Science (UCST)


Specifies how

many times an
animation- iteration-
animation 0 to Infinite
count should be

played

Normal (Default value): The animation is


played
as normal (forwards)
Specifies whether Reverse: The animation is played in
or not the reverse direction (backwards)
animation should
animation- direction Alternate: The animation is played
play in reverse on
forwards first, then backwards
alternate cycles
Alternate-reverse: The animation is

played backwards first, then forwards

None (Default value): Animation will not

apply any styles to the element before

or after it is

executing
Forwards: The element will retain the
Specifies what style values that is set by the last
values are applied keyframe (depends on animation-
animation-fill- mode by the animation direction and animation-iteration-

outside the time count)


it is executing
Backwards: The element will get the

style values that is set by the first

keyframe (depends on animation-

direction), and retain this during

the animation-delay period

40 Archana D A | Department of Computer Science (UCST)


Both: The animation will follow the rules

for both forwards and backwards,

extending the animation properties in

both directions

Specifies whether Paused: Specifies that the animation is

the animation is paused


animation- play-state
running or Running: (Default value) Specifies

paused that the animation is running

MULTIPLE ANIMATION PROPERTY EXAMPLE

Yes, an element can have multiple animations in CSS. In fact, it's common for

elements to have multiple animations applied to them to create more complex and

dynamic effects.

To apply multiple animations to an element, we can simply list each animation

separated by a comma in the animation property. For example:

.any-element {
animation: spin 3s linear, fade 5s ease-in-out;
}

In this example, the .any-element class has two animations applied to it: spin

and fade. The spin animation will rotate the element for 3 seconds using a linear

timing function, and the fade animation will fade the element in and out for 5

second using an ease-in-out timing function.

We can also specify multiple keyframe animations in a single @keyframes rule to

apply them to an element. For example:

@keyframes
spin
{
0% {transform:
rotate(Odeg);}
50% {transform: rotate(180deg);}

41 Archana D A | Department of Computer Science (UCST)


100% {transform: rotate(360deg);}

@keyframes
fade
{
0% {opacity: O;}
50% {opacity: 1;}
100% {opacity:
O;}
}

.any-element {
animation: spin 2s linear, fade 1s ease-in-out;
}

In this example, we define two @keyframes rules for the spin and fade animations,

and then apply both animations to the .any-element class using the animation

property.

SHORTHAND V/S LONGHAND PROPERTIES

SHORTHAND LONGHAND

Shorthand CSS is the creation of CSS Longhand CSS is the creation of CSS
elements with minimal code while elements with long codes while writing
writing style files. style files.

Number of loads is reduced Number of loads is increased

Properties order has its significance Properties order doesn't has its significance

Shorthand CSS files takes less time to load Longhand CSS files takes more time to load

Example: Example:

.margin { .margin {
margin: 5px 6px 7px 8px; margin-top: 5px;
} margin-right: 6px;
margin-bottom:
7px; margin-left:
8px;
}

42 Archana D A | Department of Computer Science (UCST)


UNIT 3
HTML 5 – SVG

SVG is an XML language, similar to XHTML, which can be used to draw vector
graphics. It can be used to create an image either by specifying all the lines and shapes
necessary, by modifying already existing raster images, or by a combination of both. The
image and its components can also be transformed, composited together, or filtered to change
their appearance completely.

SVG came about in 1999 after several competing formats had been submitted to the
W3C and failed to be fully ratified. SVG is supported by all major browsers.

o SVG stands for Scalable Vector Graphics. SVG is an Open Standard developed and
maintained by the W3C SVG Working Group.

o SVG is a XML based format used to draw vector images.

o It is a language for describing 2-D graphics in XML.

o Due to the vector image, if we zoom out or resize the SVG image then it will never
lose quality.

o SVG images support interactivity and animation.

o SVG Supports for event handlers. Various web browser supports SVG i.e. Chrome,
Opera, Firefox, Safari, Internet Explorer etc.

Advantages:
 It provides good printing quality at any resolution and therefore is highly usable.

 It is an Open Standard and easy to use.

 We can use any text editor to create and edit SVG images.

 It is highly scalable and never compromises on quality on resizing.

Disadvantages:
 The size of text formatted raster images is bigger than binary formatted raster images.

 Even for a simple image, the size can be large.

43 Archana D A | Department of Computer Science (UCST)


EXAMPLE

<!DOCTYPE html>
<html>
<body>
<SVG width="100" height="100">
<circle cx="50" cy="50" r="40"
stroke="green" stroke-width="4" fill="yellow" />
</SVG>
</body>
</html>
The rendering process involves the following:

o SVG images are defined within <SVG> ...... </SVG> element.

o The width and height attributes of <SVG> element is used to define the height and
width of the SVG image.

o In the above example, <circle> element is used to draw a circle.

o cx and cy attribute is used to represent the center of the circle. Its default value is
(0,0).

o r attribute is used to represent the radius of circle.

o Other attributes stroke and stroke-width is used to control the outlining of the circle.

o fill attribute is used to define the fill color of the circle.

EMBEDDING SVG IN WEB BROWSERS

Displaying SVG in web browsers like Chrome, Firefox and Internet Explorer can be done in
several ways:

 Point the browser to the URL of the SVG file.

 Embed SVG inside an HTML page

We can embed an SVG image in an HTML file in several ways:

 Using an iframe element

44 Archana D A | Department of Computer Science (UCST)


 Using an img element

 Using the SVG image as background image.

 Using an SVG element

 Using an embed element

1. iframe
Since the browsers can show SVG images if we type in the URL to the SVG image, we can
also include an SVG image in your HTML page by using an iframe.

<iframe src="mySVGImage.SVG" width="200" height="200" >

2. img
Embedding an SVG image using an img element is done just like any other type of image.
We write the URL of the SVG image in the src attribute of the img element, like this:

<img src="/SVG/circle-element-1.jsp">

The SVG image is then shown in the HTML page, just like any other image.

3. SVG as Background Images


Since the browsers treat SVG images just like bitmap images, we can use SVG images as
background images via CSS.

div {
background-image: url('my-SVG-image.SVG');
background-size : 100px 100px;
}

It may be necessary to set a background size for the SVG image, to tell the browser how to
scale it.
4. SVG Element inside HTML
Embedding an SVG image using the SVG element can be done by embedding SVG element
directly in an HTML page, like this:

<div>
<SVG>
<circle cx="40" cy="40" r="24" style="stroke:#006600; fill:#00cc00"/>

45 Archana D A | Department of Computer Science (UCST)


</SVG>
</div>

 The div element is just here to illustrate that the SVG element can be embedded
directly in HTML. The SVG element does not have to be embedded in a div element
though.
 Using the SVG element we can embed SVG directly in the HTML page, instead of
putting the SVG image in its own file. We can set the width and height of the SVG
image by adding width and height attributes to the SVG element.
 Using the SVG element we can also generate SVG directly in the browser using
JavaScript.
 Using the SVG element we can also style the SVG and its child elements using CSS,
just like we would with any other HTML. Note that the SVG elements sometimes
have different names for some of their CSS properties than HTML elements.
5. embed
In the early days of SVG we could embed SVG images using the embed element. Back then
not all browsers had native support for SVG. It is recommended to use either
the img or SVG elements instead. Here is an example embed element:

<embed src="/SVG/simple-example-1.jsp"
width="300" height="220"
type="image/SVG+xml"
pluginspage="http://www.adobe.com/SVG/viewer/install/" />

 Place this element wherever we want the SVG image to be displayed in our HTML
file. The src attribute should point to the URL of the SVG image.

Note: The pluginspage attribute, this is necessary in older browsers not capable of
displaying SVG natively. These browsers need Adobe's SVG Viewer plugin to display the
image. In Internet Explorer 7 and Firefox 3.0.5 this attribute is not necessary.

BASIC SHAPES
1. Rectangle

The rect element is used to draw a rectangle on the screen. To control the position and
shape of the rectangle on screen, there are 6 basic attributes.
x: It define the position of the top left corner of the rectangle.
46 Archana D A | Department of Computer Science (UCST)
y: It define the top position of the rectangle.

width: It defines the width of the rectangle.

height: It defines the height of the rectangle.

fill-opacity: It is used to define the opacity of the fill color. Its range can be 0 to 1.

stroke-opacity: It defines the opacity of the stroke color. Its range can be 0 to 1.

Example
<!DOCTYPE html>
<html>
<body>
<SVG width="500" height="500">
<rect x="50" y="50" width="200" height="200"
style="fill:green;stroke:orange;stroke-width:5;
fill-opacity:0.1;stroke-opacity:0.9" />
</SVG>
</body>
</html>
2. Circle
The circle element is used to draw a circle on the screen and there are 3 basic attributes
that are applicable here.

r: It defines the radius of the circle.

cx: It defines the x coordinates of the center of the circle.

cy: It defines the y coordinates of the center of the circle.


Example
<!DOCTYPE html>
<html>
<body>
<SVG height="250" width="250">
<circle cx="70" cy="70" r="40" stroke="#03ac13" stroke-
width="3" fill="#f61491" />
</SVG>
</body>
</html>

3. Ellipse
Ellipse is a more general form of the circle element. We can scale the x and y radius of
the circle separately.

47 Archana D A | Department of Computer Science (UCST)


Attribute used to draw an ellipse:
rx: It defines the horizontal radius.

ry: It defines the vertical radius.

cx: It defines the x coordinate of the center of the ellipse.

cy: It defines the y coordinate of the center of the ellipse.

Example
<!DOCTYPE html>
<html>
<body>
<SVG height="500" width="500">
<ellipse cx="250" cy="100" rx="120" ry="70"
style="fill:red;stroke:black;stroke-width:3" />
</SVG>
</body>
</html>

4. Line
The line attribute is used to draw a straight line on the screen. It has two points which
specify the start and end point of the line.
x1: It defines the start of the line on the x-axis.

y1: It defines start of the line on the y-axis.

x2: It defines the end of the line on the x-axis.

y2: It defines the end of the line on the y-axis.

Example
<!DOCTYPE html>
<html>
<body>
<SVG height="500" width="450">
<line x1="5" y1="5" x2="150" y2="150"
style="stroke:rgb(0,0,255); stroke-width:3" />
</SVG>
</body>
</html>
5. Polyline
Polyline is a connected straight line group. It has all the
points of line in one attribute.

48 Archana D A | Department of Computer Science (UCST)


Example
<!DOCTYPE html>
<html>
<body>
<SVG height="450" width="450">
<polyline points="10,20 40,30 55,45 76,125 125,135 210,200"
style="fill:none;stroke:black;stroke-width:3" />
</SVG>
</body>
</html>

In this list, each number is separated by a space, comma. Each point must contain two
numbers that define the x coordinate and the y coordinate. So the list of points (0,0), (1,1) and
(2,2) could be written as "0 0, 1 1, 2 2".

6. Path
Path is the most general shape that can be used in SVG. Through the path element, we
can draw ellipse, rectangle, polygons, circles and polylines. To control its shape there is a
single attribute. The following commands are available for path data:
Attribute Description
d Required. A set of commands which define the path.

The following commands are available for path data:

 M = moveto (move from one point to another point)


 L = lineto (create a line)
 H = horizontal lineto (create a horizontal line)
 V = vertical lineto (create a vertical line)
 C = curveto (create a curve)
 S = smooth curveto (create a smooth curve)
 Q = quadratic Bézier curve (create a quadratic Bézier curve)
 T = smooth quadratic Bézier curveto (create a smooth quadratic
Bézier curve)
 A = elliptical Arc (create a elliptical arc)
 Z = closepath (close the path)

Note: All of the commands above can also be expressed in lower case. Upper case means
absolutely positioned, lower case means relatively positioned.

49 Archana D A | Department of Computer Science (UCST)


Example
<!DOCTYPE html>
<html>
<body>
<SVG height="450" width="450">
<path d="M250 10 L100 200 L400 200 Z" />
</SVG>
</body>
</html>
Explanation
This code defines a path that starts at position 250,10 with a line to position 100,200
then from there, a line to 400,200 and finally closing the path back to 250,10.

SVG GRADIENTS
A gradient is a smooth transition from one color to another. In addition, several color
transitions can be applied to the same element.

There are two main types of gradients in SVG:

 Linear

 Radial

1. SVG Linear Gradient - <linearGradient>


The <linearGradient> element is used to define a linear gradient.

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

Linear gradients can be defined as horizontal, vertical or angular gradients:

 Horizontal gradients are created when y1 and y2 are equal and x1 and x2 differ

 Vertical gradients are created when x1 and x2 are equal and y1 and y2 differ

 Angular gradients are created when x1 and x2 differ and y1 and y2 differ

Linear gradients change along a straight line. To insert one, we need to create a
<linearGradient> node inside the <defs> section of our SVG file.

Example

<SVG width="120" height="240">


<defs>
<linearGradient id="Gradient1"
x1="0" x2="0" y1="0" y2="1">
<stop offset="0%" stop-color="red" />
50 Archana D A | Department of Computer Science (UCST)
<stop offset="50%" stop-color="black"
stop-opacity="0" />
<stop offset="100%" stop-color="blue" />
</linearGradient>
</defs>
<rect x="10" y="10" rx="15" ry="15" width="100" height="100" fill="url(#Gradient1)" />
</SVG>

Above is an example of a linear gradient being applied to a <rect> element. Inside the
linear gradient are several <stop> nodes. These nodes tell the gradient what color it should be
at certain positions by specifying an offset attribute for the position, and a stop-
color attribute. This can be assigned directly or through CSS.

The two methods have been intermixed for the purposes of this example. For instance,
this one tells the gradient to start at the color red, change to transparent-black in the middle,
and end at the color blue. We can insert as many stop colors as we like to create a blend that's
as beautiful or hideous as we need, but the offsets should always increase from 0% (or 0 if we
want to drop the % sign) to 100% (or 1).

2. Radial Gradient - <radialGradient>

Radial gradients are similar to linear ones but draw a gradient that radiates out from a point.
To create one we add a <radialGradient> element to the <defs> section of our document.

Example

<!DOCTYPE html>
<html>
<body>
<SVG height="150" width="500">
<defs>
<radialGradient id="grad1" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
<stop offset="0%" style="stop-color:rgb(255,255,255);stop-opacity:0" />
<stop offset="100%" style="stop-color:rgb(0,0,255);stop-opacity:1" />
</radialGradient>
</defs>
<ellipse cx="200" cy="70" rx="85"
ry="55" fill="url(#grad1)" />
Sorry, your browser does not support inline SVG.
</SVG>
</body>
</html>

51 Archana D A | Department of Computer Science (UCST)


STAR IN HTML5 SVG

<!DOCTYPE html>
<html>
<head>
<title>HTML5 SVG Polygon Star</title>
</head>
<body>
<h2>HTML5 SVG Star</h2>
<SVG id = "star" width = "300" height = "300">
<polygon points="100,10 40,180 190,60 10,60
160,180" fill="yellow" stroke=”red”/>
</SVG>
</body>
</html>

52 Archana D A | Department of Computer Science (UCST)


UNIT – 4
HTML5 – CANVAS
<canvas> is an HTML element which can be used to draw graphics via scripting
(usually JavaScript). This can, for instance, be used to draw graphs, combine photos, or
create simple animations.

First introduced in WebKit by Apple for the macOS Dashboard, <canvas> has since
been implemented in browsers. Today, all major browsers support it.

The <canvas> element is not supported in some older browsers, but is supported in
recent versions of all major browsers. The default size of the canvas is 300 pixels × 150
pixels (width × height). But custom sizes can be defined using the
HTML height and width property. In order to draw graphics on the canvas we use a
JavaScript context object, which creates graphics on the fly.

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 (Internet explorer Version8) does not support canvas natively.

53 Archana D A | Department of Computer Science (UCST)


HTML CANVAS DRAWING

Step 1: Declare Canvas

<canvas id="myCanvas" width="200" height="100" style="border:1px solid grey;">

</canvas>

Step 2: Define Canvas

At first we need to find the <canvas> element. This is done by using the HTML DOM
method getElementById()

Var c = document.getElementById("myCanvas");

Step 3: Create a Drawing Object

Then we need a drawing object for the canvas. So getContext() is used, which is a built-in
HTML object, with properties and methods for drawing.

Var ctx = c.getContext("2d");

Step 4: Create a Drawing path

From here onwards we need to access variable we created for canvas object and then we need
to use any of drawing styles. (Here ‘ctx’ is used as canvas object)

ctx.beginpath();

Step 5: Create any Drawing shapes

Using various methods we can create various shapes in Canvas where Javascript is used to
draw any shapes.

Step 6: Stroke it (Do the Drawing)

ctx.stroke();

EXAMPLE:

<!DOCTYPE html>
<html>
<body>
<h1>HTML5 Canvas</h1>
<h2>Draw a Line</h2>
<canvas id="Sample" width="300" height="200" style="border:2px solid black;">
</canvas>
<script>
// Create a canvas:
const canvas = document.getElementById("sample");
54 Archana D A | Department of Computer Science (UCST)
const ctx = canvas.getContext("2d");
// Define a new path:
ctx.beginPath();
// Define a start point
ctx.moveTo(0,0);
// Define an end point
ctx.lineTo(200,100);
// Draw it
ctx.stroke();
</script>
</body>
</html>
1. HTML5 CANVAS - DRAWING RECTANGLES
There are three methods to draw rectangle on the canvas
Sl. No Method with Description
1
fillRect(x,y,width,height)
This method draws a rectangle with color filled.
2
strokeRect(x,y,width,height)
This method draws a outline to a drawn rectangle.
3
clearRect(x,y,width,height)
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.

<!DOCTYPE HTML>
<html>
<head>
<script>
// Get the canvas element using the DOM
var c = document.getElementById('sample');

// use getContext to use the canvas for drawing


var ctx = c.getContext('2d');

// Draw shapes
ctx.fillRect(25,25,100,100);
ctx.clearRect(45,45,60,60);
ctx.strokeRect(50,50,50,50);

</script>
</head>
<body>
<canvas id = "Sample"></canvas>
</body>
</html>

55 Archana D A | Department of Computer Science (UCST)


2. HTML5 CANVAS - DRAWING LINES

1 beginPath()
This method resets the current path.
2 moveTo(x, y)
This method creates a new subpath with the given point.
3 closePath()
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.
4 fill()
This method fills the subpaths with the current fill style.
5
stroke()
This method strokes the subpaths with the current stroke style.
6 lineTo(x, y)
This method adds the given point to the current subpath, connected to the
previous one by a straight line.

Example:

<!DOCTYPE html>
<html>
<body>
<canvas id="Sample" width="300" height="200" style="border:1px solid grey;">
</canvas>
<script>
// Create a canvas:
var c = document.getElementById("Sample");
var ctx = c.getContext("2d");
// Define a new path:
ctx.beginPath();
// Define a start point
ctx.moveTo(50,10);
// Define an end point
ctx.lineTo(150,150);
// Draw it
ctx.stroke();
</script>
</body>
</html>

56 Archana D A | Department of Computer Science (UCST)


LINEWIDTH PROPERTY
The lineWidth property defines the line width to use, when drawing in the canvas context.
It must be set before calling the stroke() method.

STROKESTYLE PROPERTY

The strokeStyle property defines the style to use, when drawing in the canvas context.
It must be set before calling the stroke() method.

LINECAP PROPERTY
The lineCap property defines the cap style of the line (butt, round or square). The default
is square. It must be set before calling the stroke() method.

3. HTML5 CANVAS - DRAWING CIRCLE


To draw a circle on a canvas, use the following methods:

 beginPath() - begins a path

 arc(x,y,r,startangle,endangle) - creates an arc/curve. To create a circle with arc(): Set


start angle to 0 and end angle to 2*Math.PI. The x and y parameters define the x- and
y-coordinates of the center of the circle. The r parameter defines the radius of the
circle.

Example:

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="200" height="200" style="border:1px solid #d3d3d3;">
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(100,100,50,0,2*Math.PI);
ctx.stroke();
</script>
</body>
</html>

57 Archana D A | Department of Computer Science (UCST)


4. HTML5 CANVAS - CREATE GRADIENTS
SL. NO. METHOD AND DESCRIPTION
1 addColorStop(offset, color)

This method adds a color stop with the given color to the gradient at the given offset.
Here 0.0 is the offset at one end of the gradient, 1.0 is the offset at the other end.

2 createLinearGradient(x0, y0, x1, y1)

This method returns a CanvasGradient object that represents a linear gradient 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 that
3 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.

LINEAR GRADIENT
<!DOCTYPE HTML>
<html>
<body>
<canvas id = "Sample">
</canvas>
<Script>
// get the canvas element using the DOM
var c = document.getElementById('Sample');

// use getContext to use the canvas for drawing


var ctx = c.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');

// assign gradients to fill and stroke styles

58 Archana D A | Department of Computer Science (UCST)


ctx.fillStyle = lingrad;
OUTPUT:
ctx.strokeStyle = lingrad;

// draw shapes
ctx.fillRect(10,10,130,130);
ctx.strokeRect(50,50,50,50);
</script>
</body>
</html>

RADIAL GRADIENT
<!DOCTYPE HTML>
<html>
<body>
<canvas id = "Sample"></canvas>
<script>
// get the canvas element using the DOM
var c = document.getElementById('sample');

// use getContext to use the canvas for drawing


var ctx = c.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)');

// draw shapes
ctx.fillStyle = radgrad;
ctx.fillRect(0,0,150,150);
</script>

</body>
</html>

OUTPUT

59 Archana D A | Department of Computer Science (UCST)


5. HTML5 CANVAS - DRAWING PATHS
SL.
METHOD AND DESCRIPTION
NO.
1
beginPath()
This method resets the current path.
2
moveTo(x, y)
This method creates a new subpath with the given point.
3
closePath()
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.
4
fill()
This method fills the subpaths with the current fill style.
5
stroke()
This method strokes the subpaths with the current stroke style.
6
arc(x, y, radius, startAngle, endAngle, anticlockwise)
Adds points to the subpath such that the arc described by the circumference of the
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:
<!DOCTYPE HTML>
<html>
<body>
<canvas id = "Sample">
</canvas>
<script>
// get the canvas element using the DOM
var c = document.getElementById(‘Sample');

// use getContext to use the canvas for drawing


var ctx = c.getContext('2d');

// Draw shapes
ctx.beginPath();
ctx.arc(75,75,50,0,Math.PI*2,true); // For Outer circle

ctx.moveTo(110,75);
ctx.arc(75,75,35,0,Math.PI,false); // To draw Mouth

ctx.moveTo(65,65);
ctx.arc(60,65,5,0,Math.PI*2,true); // To draw Left eye

60 Archana D A | Department of Computer Science (UCST)


ctx.moveTo(95,65);
ctx.arc(90,65,5,0,Math.PI*2,true); // To draw Right eye
ctx.stroke();

</script>
</body>
</html>

6. HTML5 CANVAS - DRAWING BEZIER CURVES


S.NO. METHOD AND DESCRIPTION
1
beginPath()
This method resets the current path.
2
moveTo(x, y)
This method creates a new subpath with the given point.
3
closePath()
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.
4
fill()
This method fills the subpaths with the current fill style.
5
stroke()
This method strokes the subpaths with the current stroke style.
6
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
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.

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.

61 Archana D A | Department of Computer Science (UCST)


Example
<!DOCTYPE HTML>
<html>
<body>
<canvas id = "Sample">
</canvas>
<script>
// get the canvas element using the DOM
var c = document.getElementById('Sample');

// use getContext to use the canvas for drawing


var ctx = c.getContext('2d');
ctx.lineWidth= "5";
ctx.beginPath();
ctx.moveTo(10,150);
ctx.bezierCurveTo(30,40,60,150,200,80);
ctx.fillStyle="yellow";
ctx.strokeStyle= "blue";
ctx.fill();
ctx.stroke();

//To see the control points


ctx.lineWidth= "1";
ctx.beginPath();
ctx.moveTo(10,150);
ctx.lineTo(30,40);
ctx.lineTo(60,150);
ctx.lineTo(200,80);
ctx.strokeStyle= 'red';
ctx.stroke();
</script>
</body>
</html>

OUTPUT:

62 Archana D A | Department of Computer Science (UCST)


7. HTML5 CANVAS - DRAWING QUADRATIC CURVES
SL.
METHOD AND DESCRIPTION
NO.
1
beginPath()
This method resets the current path.
2
moveTo(x, y)
This method creates a new subpath with the given point.
3
closePath()
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.
4
fill()
This method fills the subpaths with the current fill style.
5
stroke()
This method strokes the subpaths with the current stroke style.
6
quadraticCurveTo(cpx, cpy, x, y)
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.
EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<canvas id="Sample" width="300" height="150" style="border:1px solid grey"></canvas>
<script>
const c = document.getElementById("Sample");
const ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.quadraticCurveTo(20, 100, 200, 20);
ctx.stroke();

ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(20, 100);
ctx.lineTo(200, 20);

63 Archana D A | Department of Computer Science (UCST)


ctx.strokeStyle='green';
ctx.stroke();
</script>
</body>
</html>
OUTPUT:

8. HTML5 CANVAS - USING IMAGES


SL.NO. METHOD AND DESCRIPTION
1
beginPath()
This method resets the current path.
2
moveTo(x, y)
This method creates a new subpath with the given point.
3
closePath()
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.
4
fill()
This method fills the subpaths with the current fill style.
5
stroke()
This method strokes the subpaths with the current stroke style.
6
drawImage(image, dx, dy)
This method draws the given image onto the canvas. Here image is a reference to
an image or canvas object. x and y form the coordinate on the target canvas where
our image should be placed.
<!DOCTYPE html>
<html>
<body>
<p>Original Image</p>
<img id="Pic1" width="220" height="277" src="pic_the_scream.jpg" alt="Sample Picture">
<p>Canvas:</p>

64 Archana D A | Department of Computer Science (UCST)


<canvas id="Sample" width="240" height="297" style="border:1px solid grey;"></canvas>
<script>
const c = document.getElementById("Sample");
const ctx = c.getContext("2d");
const img = document.getElementById("Pic1");
ctx.drawImage(img, 10, 10);
</script>
</body>
</html>

OUTPUT:

65 Archana D A | Department of Computer Science (UCST)


UNIT 5
CANVAS FONT PROPERTY
The HTML canvas font Property is used to change the properties of the Text content
of the <canvas> element. The font Property has a Default value i.e., 10px sans-serif.
Syntax:
ctx.font="font-style font-variant font-weight font-size font-family";
Property Values:
 font-style: It is used to specify the font style of an HTML element. It can be
“normal, italic or oblique”.
 font-variant: It is used to create the small-caps effect. It can be “normal or small-
caps”.
 font-weight: It is used to set the boldness of the font. Its value can be
“normal, bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800 and 900”.
 font-size: It is used to set the font size of an HTML element. The font-size can be set
in different ways like in “pixels, percentage, em or we can set values like small, large”
etc.
 font-family: It is used to set the font type of an HTML element. It holds several font
names as a fallback
Ex: sans-serif, Arial, Verdana, Courier new, Times New Roman, serif etc.
HTML CANVAS TEXT
Drawing Text on the Canvas
To draw text on a canvas, the most important property and methods are:
 font - defines the font properties for the text
 fillText(text,x,y) - draws "filled" text on the canvas
 strokeText(text,x,y) - draws text on the canvas with outline of text is filled but inside
of text will not be filled.

NOTE: To fill text, we need to use property fillStyle before fillText property. Similarly before
using strokeText we need to use strokeStyle property. If we directly use fillText or
strokeText then the default value i.e., “Black” will be filled to text.

66 Archana D A | Department of Computer Science (UCST)


1. Using fillText()
<!DOCTYPE html>
<html>
<body>
<canvas id="sample" width="250" height="100" style="border:1px solid grey;"></canvas>
<script>
var c = document.getElementById("sample");
var ctx = c.getContext("2d");
ctx.font = "30px Courier New";
ctx.fillStyle=”red”;
ctx.fillText("Hi everyone",20,50);
</script>
</body>
</html>

2. Using strokeText()
<!DOCTYPE html>
<html>
<body>
<canvas id="sample" width="200" height="100" style="border:1px solid grey;"></canvas>
<script>
var c = document.getElementById("sample");
var ctx = c.getContext("2d");
ctx.font = "30px Verdana";
ctx.strokeStyle="blue";
ctx.strokeText("Hello World",10,50);
</script>
</body>
</html>

OTHER TEXT RELATED PROPERTIES

SL. No. PROPERTY AND DESCRIPTION


textAlign = “value”
1 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
2
change the baseline alignment. The possible values are top, hanging, middle,
alphabetic, ideographic and bottom.

67 Archana D A | Department of Computer Science (UCST)


TEXTALIGN PROPERTY

TEXTBASELINE PROPERTY

CANVAS createPattern() METHOD


 The createPattern() method repeats the specified element in the specified direction.
 The element can be an image, video, or another <canvas> element.
 The repeated element can be used to draw/fill rectangles, circles, lines etc.

JavaScript syntax: ctx.createPattern(image, "repeat|repeat-x|repeat-y|no-repeat");

PROPERTY VALUES

PROPERTIES DESCRIPTION

image Specifies the image, canvas, or video element of the pattern to use

repeat It’s Default. This repeats pattern both horizontally and vertically

repeat-x The pattern repeats only horizontally

repeat-y The pattern repeats only vertically

no-repeat The pattern will be displayed only once (no repeat)

<!DOCTYPE html>
68 Archana D A | Department of Computer Science (UCST)
<html>
<body>
<p>Image to use:</p>
<img src="../jsref/img_lamp.jpg" id="lamp" width="32" height="32">
<p>
<button onclick="draw('repeat')">Repeat</button>
<button onclick="draw('repeat-x')">Repeat-x</button>
<button onclick="draw('repeat-y')">Repeat-y</button>
<button onclick="draw('no-repeat')">No-repeat</button>
</p>
<canvas id="sample" width="300" height="150" style="background:black;">
</canvas>
<script>
function draw(direction) {
const c = document.getElementById("sample");
const ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
const img = document.getElementById("lamp")
const p = ctx.createPattern(img, direction);
ctx.rect(0, 0, 150, 100);
ctx.fillStyle = p;
ctx.fill();
}
</script>
</body>
</html>
OUTPUT
1. Repeat 2. Repeat-x

69 Archana D A | Department of Computer Science (UCST)


3. Repeat-y 4. No-repeat

CREATE SHADOWS
HTML5 canvas provides capabilities to create nice shadows around the drawings. All
drawing operations are affected by the four global shadow attributes.

SL. No. Property and Description

1 shadowColor = value

This property returns the current shadow color and can be set, to change the
shadow color.

2 shadowOffsetX = value

This property returns the current shadow offset X and can be set, to change the
shadow offset X.

3 shadowOffsetY = value

This property returns the current shadow offset Y and can be set, change the
shadow offset Y.

4 shadowBlur = value

This property returns the current level of blur applied to shadows and can be set,
to change the blur level.

SAVE AND RESTORE STATES


SL. No. Method and Description

1 save()
This method pushes the current state onto the stack..
2 restore()
This method pops the top state on the stack, restoring the context to that state.

70 Archana D A | Department of Computer Science (UCST)


<!DOCTYPE html>
<html>
<body>
<canvas id="samples" width="300" height="150" style="border:1px solid grey"></canvas>
<script>
const c = document.getElementById("sample");
const ctx = c.getContext("2d");
// Draw
ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 50, 50);
// Save the state
ctx.save();
// Draw new
ctx.fillStyle = "red";
ctx.fillRect(100, 10, 50, 50);
// Restore saved state
ctx.restore();
// Draw new
ctx.fillRect(200, 10, 50, 50);
</script>
</body>
</html>

CANVAS TRANSFORM

Syntax: context.transform(a, b, c, d, e, f)

Property values

Properties Description

a Scales the drawing horizontally

b Skew the drawing horizontally

c Skew the drawing vertically

d Scales the drawing vertically

e Moves the drawing horizontally

f Moves the drawing vertically

71 Archana D A | Department of Computer Science (UCST)


<!DOCTYPE html>
<html>
<body>
<canvas id="sample" width="300" height="150" style="border:1px solid grey"></canvas>
<script>
var c = document.getElementById("sample");
var ctx = c.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, 250, 100);

ctx.transform(1, 0.5, -0.5, 1, 30, 10);


ctx.fillStyle = "yellow";
ctx.fillRect(0, 0, 250, 100);

ctx.transform(1, 0.5, -0.5, 1, 30, 10);


ctx.fillStyle = "green";
ctx.fillRect(0, 0, 250, 100);
</script>
</body>
</html>
CANVAS TRANSLATE
Syntax: context.translate(x, y)

Note: We can specify one or both parameters.


PROPERTY DESCRIPTION
x Value to add to horizontal (x) coordinate
y Value to add to vertical (y) coordinate

<!DOCTYPE html>
<html>
<body>
<canvas id="sample" width="300" height="200" style="border:1px solid grey"></canvas>
<script>
var c = document.getElementById("sample");
var ctx = c.getContext("2d");
ctx.fillRect(10, 10, 100, 70);
ctx.translate(100, 80);
ctx.fillRect(10, 10, 100, 70);
</script>
</body>
</html>

72 Archana D A | Department of Computer Science (UCST)


CANVAS ROTATE() METHOD
Syntax:
context.rotate(angle)
Parameter Values:
 angle: It stores the rotation angle in radians. If the angle is given in the form of a
degree then it converts into a radian by using the formula degree*Math.PI/180.
<!DOCTYPE html>
<html>
<body>
<canvas id="sample" width="300" height="150" style="border:1px solid grey"></canvas>
<script>
var c = document.getElementById("sample");
var ctx = c.getContext("2d");
ctx.rotate(20 * Math.PI / 180);
ctx.fillRect(50, 20, 100, 50);
</script>
</body>
</html>

CANVAS SCALE() METHOD


Syntax

context.scale(scalewidth, scaleheight)

PROPERTIES VALUES

PROPERTIES DESCRIPTION
scalewidth Scales the width (1=100%, 0.5=50%, 2=200%)
scaleheight Scales the height (1=100%, 0.5=50%, 2=200%)

<!DOCTYPE html>
<html>
<body>
<canvas id="sample" width="300" height="150" style="border:1px solid grey"></canvas>
<script>
var c = document.getElementById("sample");
var ctx = c.getContext("2d");
ctx.strokeRect(5, 5, 25, 15);
ctx.scale(2, 2);
ctx.strokeRect(5, 5, 25, 15);
</script>
</body>
</html>

73 Archana D A | Department of Computer Science (UCST)


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 −
SL. No. Method and Description
1 setInterval(callback, time);
This method repeatedly executes the supplied code after a given time milliseconds.

2 setTimeout(callback, time);
This method executes the supplied code only once after a given time milliseconds.

<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" style='background-color:#EEE;' width='500px' height='200px'/>
<script>
var x = 0;
function drawIt() {
window.requestAnimationFrame(drawIt);
var canvas = document.getElementById('canvas');
var c = canvas.getContext('2d');
c.clearRect(0,0,canvas.width,canvas.height);
c.fillStyle = "red";
c.fillRect(x,50,80,100);
x+=2;
}
drawIt();
</script>
</body>
</html>

CANVAS GLOBAL COMPOSITE OPERATION PROPERTY

The globalCompositeOperation property sets or returns how a source are drawn over a
destination. Source means drawings we are about to draw on the canvas, destination means
drawings that are already drawn on the canvas.

Syntax
context.globalCompositeOperation = "value"

74 Archana D A | Department of Computer Science (UCST)


PROPERTY VALUES

Value Description
source-over Default
Displays the source over the destination
source-atop Displays the source on top of the destination. The part of the source
image that is outside the destination is not shown
source-in Displays the source in the destination. Only the part of the source
that is INSIDE the destination is shown, and the destination is
transparent
source-out Displays the source out of the destination. Only the part of the
source that is OUTSIDE the destination is shown, and the destination
is transparent
destination- Displays the destination over the source
over
destination- Displays the destination on top of the source. The part of the
atop destination that is outside the source is not shown
destination- Displays the destination in the source. Only the part of the
in destination that is INSIDE the source is shown, and the source is
transparent
destination- Displays the destination out of the source. Only the part of the
out destination that is OUTSIDE the source is shown, and the source is
transparent
lighter Displays the source + the destination
copy Displays the source. The destination is ignored
xor The source is combined by using an exclusive OR with the destination

75 Archana D A | Department of Computer Science (UCST)

You might also like