CM&a Complete Notes
CM&a Complete Notes
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.
<acronym> <abbr>
<applet> <object>
<basefont> CSS
<big> CSS
<center> CSS
<dir> <ul>
<font> CSS
<frame>
<frameset>
<noframes>
<isindex>
<tt> CSS
<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.
<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.
<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.
<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.
<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.
Advantages:
HTML 5 in integration with CSS, JavaScript, etc. can help build beautiful websites.
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.
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”>
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”.
Checkbox Control
The checkbox control is used to check multiple options from given checkboxes.
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.
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 tables allow web developers to arrange data into rows and columns.
Tag Description
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.
<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.
Start specifies from where has numbering has to be start and type specifies
way of numbering.
<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.
The <img> tag is empty, it contains attributes only, and does not have a closing tag.
Syntax
ATTRIBUTES DESCRIPTION
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.
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.
DISADVANTAGES OF FRAMES
Some smaller devices cannot cope with frames often because their screen is not big
enough to be divided up.
The browser's back button might not work as the user hopes.
There are still few browsers that do not support frame technology.
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
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.
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.
</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.
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
BORDER PROPERTIES
Property Description Values
Sets the style of the four none, hidden, dotted, dashed, solid, double,
border-style
borders groove, ridge, inset, outset, inherit
Specifies the font size of xx-small, x-small, small, medium, large, x-large,
font-size
text xx-large, smaller, larger, length, %, 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.
Ex:
<head>
<style>
#para1 {
text-align: center;
color: blue;
}
</style>
</head>
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>
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>
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
Box model
Text effects
Selectors
Animations
2D/3D transformations
ADVANTAGES OF CSS3
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.
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.
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: 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.
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.
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.
Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
= Assign 10+10 = 20
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-
else.
e.g.,document.write("Answer:"+result+"");
1) Using innerHTML
• 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>
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.
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.
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 paragraph
ii. Confirm
Opens a dialog box and displays the parameter and two buttons, OK and Cancel
if (confirm("Press a button!"))
{
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
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.
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
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
animation out of what we have, we need a smooth transition that creates all the
interpolation.
This interpolation, which occurs over a period of time that we specify, would
1. CSS animation
2. CSS transition
3. Scripted animation
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
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
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
2. CSS transitions
state, end state, and duration. The rest, such as interpolating between the two
If we want full control over what our animation does right down to
THERE ARE 3 MAJOR PROPERTIES WHICH MAKES ANIMATION TO TAKES PLACE ON WEB
1. Transformation
2. Transition
3. Keyframes
1. CSS TRANSFORMS
These are a collection of functions that allow to shape elements in particular ways:
Transform properties
• is for 3d settings
• 2 parameters: first value is for the x axis, second for they axis.
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%);}
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
Example:
@keyframes rotate {
0% {transform: rotate(0deg);}
100%{ transform:
rotate(180deg);}
c) SCALE
The scale() function allows to resize an element. It can either expand or shrink it. The
function accepts either:
• 2 parameters: the first value resizes the element horizontally, the second
one vertically
• 0: the element basically disappears (as its height and width are equal to zero)
@keyframes scale {
0% {transform: scale(1);}
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()
second one vertically And like rotate(), skew() only accepts angle values like
34 Archana D A | Department of Computer Science (UCST)
degrees deg.
Example:
@keyframes skew {
0% { transform: skew(0deg);}
20% { transform: skew(10deg);}
40% { transform: skew(45deg);}
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
CSS Transitions can be controlled through shorthand transition property. This is the
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:
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
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
c) Transition-timing-function
computed. Timing functions determine how intermediate values of the transition are
calculated. Most timing functions can be specified by providing the graph of the
• 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
d) Transition-delay
Defines how long to wait between the time a property is changed and the transition
actually begins.
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 {
#delay:hover {
font-family: "Lucida Console", "Courier New", monospace;
}
.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;
}
<!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
To use keyframes, create a @keyframes rule with a name that is then used by
Each @keyframes rule contains a style list of keyframe selectors, which specify
percentages along the animation when the keyframe occurs, and a block containing
animation name.
selectors.
• css-styles: The css-styles defines the one or more legal or applicable CSS style
properties.
ANIMATION PROPERTIES
CSS Syntax
<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
many times an
animation- iteration-
animation 0 to Infinite
count should be
played
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-
both directions
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.
.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
@keyframes
spin
{
0% {transform:
rotate(Odeg);}
50% {transform: rotate(180deg);}
@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 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.
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;
}
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 Due to the vector image, if we zoom out or resize the SVG image then it will never
lose quality.
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.
We can use any text editor to create and edit SVG images.
Disadvantages:
The size of text formatted raster images is bigger than binary formatted raster images.
<!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 The width and height attributes of <SVG> element is used to define the height and
width of the SVG image.
o cx and cy attribute is used to represent the center of the circle. Its default value is
(0,0).
o Other attributes stroke and stroke-width is used to control the outlining of the circle.
Displaying SVG in web browsers like Chrome, Firefox and Internet Explorer can be done in
several ways:
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.
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.
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"/>
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.
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.
3. Ellipse
Ellipse is a more general form of the circle element. We can scale the x and y radius of
the circle separately.
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.
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.
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.
Note: All of the commands above can also be expressed in lower case. Upper case means
absolutely positioned, lower case means relatively positioned.
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.
Linear
Radial
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).
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
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).
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>
<!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>
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 <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 −
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
// drawing code here
} else {
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.
</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");
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.
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();
Using various methods we can create various shapes in Canvas where Javascript is used to
draw any shapes.
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');
// 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>
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>
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.
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>
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.
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.
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');
lingrad.addColorStop(0, '#00ABEB');
lingrad.addColorStop(0.5, '#fff');
lingrad.addColorStop(0.5, '#66CC00');
lingrad.addColorStop(1, '#fff');
// 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');
// 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
EXAMPLE:
<!DOCTYPE HTML>
<html>
<body>
<canvas id = "Sample">
</canvas>
<script>
// get the canvas element using the DOM
var c = document.getElementById(‘Sample');
// 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
</script>
</body>
</html>
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.
OUTPUT:
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);
OUTPUT:
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.
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>
TEXTBASELINE PROPERTY
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
<!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
CREATE SHADOWS
HTML5 canvas provides capabilities to create nice shadows around the drawings. All
drawing operations are affected by the four global shadow attributes.
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.
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.
CANVAS TRANSFORM
Syntax: context.transform(a, b, c, d, e, f)
Property values
Properties Description
<!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>
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>
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>
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"
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