You are on page 1of 130

Chapter 1: Introduction to Data Visualization

Subject: Data Visualization


( 3160717)
Syllabus

2
Syllabus

3
Syllabus

4
Syllabus

5
Reference Books:
1. Jon Raasch, Graham Murray, Vadim Ogievetsky, Joseph Lowery, “JavaScript and
jQuery for Data Analysis and Visualization”, WROX
2. Ritchie S. King, Visual storytelling with D3” Pearson
3. Ben Fry, "Visualizing data: Exploring and explaining data with the processing
environment", O'Reilly, 2008.
4. A Julie Steele and Noah Iliinsky, Designing Data Visualizations: Representing
Informational Relationships, O'Reilly
5. Andy Kirk, Data Visualization: A Successful Design Process, PAKT
6. Scott Murray, Interactive Data Visualization for Web, O'Reilly
7. Nathan Yau, "Data Points: Visualization that means something", Wiley, 2013.
8. Tamara Munzner, Visualization Analysis and Design, AK Peters Visualization Series,
CRC Press, Nov. 2014
6
Contents
● Introduction
● Data Acquisition and visualizing
● Applications of Data Visualization
● Keys factors of Data Visualization (Control of Presentation, Faster and Better
JavaScript processing, Rise of HTML5, Lowering the implementation Bar)
● Exploring the Visual Data Spectrum:
○ charting Primitives (Data Points, Line Charts, Bar Charts, Pie Charts, Area Charts)
○ Exploring advanced Visualizations (Candlestick Charts, Bubble Charts, Surface Charts, Map Charts,
Infographics)
○ Making use of HTML5 CANVAS
○ Integrating SVG

7
Introduction to Data Visualization
● Data visualization is the graphical representation of information and data.
● Converting raw data to a form that is viewable and understandable to humans.
● Visualization transforms data into images that effectively and accurately
represent information about the data. – said by Schroeder et al. The Visualization
Toolkit, 2nd ed. 1998
● By using visual elements like charts, graphs, and maps, data visualization tools
provide an accessible way to see and understand trends, outliers, and patterns in
data.

8
Invisible data->visible interpretation
● Turning invisible into visible that people can understand
● E.g. big data human cannot understand but its chart/graph can easily explain
behavior of data.
Example:

9
What Does Visualization Do?
● Three types of goals for visualization
○ to explore
■ Nothing is known,
■ Vis. used for data exploration
○ to analyze
■ There are hypotheses
■ Vis. used for Verification or Falsification
○ to present
■ “everything” known about the data,
■ Vis. used for Communication of Results

10
The advantages and benefits of good data visualization
● Faster Action:
○ The human brain tends to process visual information far more easily than written information.
○ Use of a chart or graph to summarize complex data ensures faster comprehension of relationships
than cluttered reports or spreadsheets.
● Communicate Findings in Constructive Ways
● Understand Connections Between Operations and Results
● Embrace Emerging Trends
● Create New Discussion

11
Explained Relation among two variables

12
A Visualization Pipeline

13
Visualization Process in detail
● Acquire- Obtain the data, whether from a file on a disk or a source over a
network.
● Parse- Provide some structure for the data’s meaning, and order it into
categories.
● Filter- Remove all but the data of interest. Apply methods from statistics or data
mining as a way to discern patterns or place the data in mathematical
context.
● Represent- Choose a basic visual model, such as a bar graph, list, or tree.
● Refine- Improve the basic representation to make it clearer and more visually
engaging.
● Interact- Add methods for manipulating the data or controlling what
features are visible.
14
Acquiring and Visualizing Data
● The first step in visualizing data is to load it into our application.
● Typical data sources might be a
○ file on a disk
○ stream from a network,
○ digitized signal (e.g., audio or sensor readings).

15
Acquiring stages:
● Unless you are generating your own data, you have to find a good source for the
data you want.
● If you don’t own the data, you have to make sure you have the right to use it.
● You may have to go through contortions( वकृ त) to extract the data from a web
page or other source that wasn’t set up to make it easy for your application.
● You have to download the data, which may present difficulties if the volume is
large, especially if it’s fast-changing.
● By following techniques data are converted to proper format
○ Modulation and sampling
○ Digitization and coding
○ File formats
■ data can be shared using nonstandard text files or existing standards: csv, xml, AnIML

16
Simultaneous acquisition and visualization
● E.g.getting data from fb and making its visualization

17
Data Enhancement
● Decide important aspects or features
● We must somehow turn our raw dataset into more appropriate
representations---enriched datasets
● Data filtering or data enriching, two tasks
○ Extract relevant information, e.g. extracting name, address for less attendance data of a student,
that time marks of each semester are irrelevant
○ Enriched with high-level information that supports a given task, e.g. Medical data-- noise data
removal; enhancement of certain material data, etc
● The input is raw dataset whereas output is enriched/enhanced dataset

18
Visualization mapping
● Once we have the needed data, we must map it to the visual domain.
● Mapping function
○ Map: D->Dv
○ D: dataset
○ Dv: dataset of visual features
● Comparison about mapping and rendering
○ Mapping: convert “invisible” to “visible” representations;
○ Rendering: simulates the physical process of lighting a “visible” 2D/3D scene.

19
Rendering ND->2D
● Data are transformed to image data.
● The rendering operation is the final step of the visualization process.
● It takes the 3D scene created by the mapping operation, together with several
user-specified viewing parameters such as the viewpoint and lighting, and
renders it to produce the desired images.
● In typical visualization applications, viewing parameters are considered part of
the rendering operation. This allows users to interactively navigate and examine
the rendered result of a given visualization.

20
Types of Data Visualization
● Scientific Visualization
○ specifically concerned with data that has a well-defined representation in 2D or 3D space
○ Structural Data
○ Seismic, Medical
● Information Visualization
○ No inherent structure
○ News, stock market, facebook connections
● Visual Analytics
○ Use visualization to understand and synthesize large amounts of multimodal data
○ audio, video, text, images, networks of people

21
Scientific Visualization
● Specifically
concerned with data
that has a
well-defined
representation in 2D
or 3D space

22
Information Visualization
● Concerned with data
that does not have a
well-defined
representation in 2D
or 3D space (i.e.,
“abstract data”).

23
Visual Analytics

● Multimodal data -audio clips, video, photographs, transcripts, …

24
Modes of Visualization - comparison
Visualization User Graphics Target Medium
mode Interaction rendering

Interactive User controls Real-time Individual or Software or


visualization everything, rendering collaborators internet
including
dataset

Interactive User can filter or Real-time Mass audience Internet


storytelling inspect details rendering
of preset
datasets

Presentation User only Precomputed Colleagues, mass Slide shows,


visualization observes rendering audience videos

25
Applications of Data Visualization
● Retail Banking
● Government
● Insurance
● Health Care and Medicine
● Telecommunications
● Transportation
● Capital Markets
● Asset Management

26
Online Data Visualization Websites
Got from Coursera course on Data Visualization

● DataHero
● Plotly
● Number Picture
● Polychart
● Juice Analytics
● Weave
● Datavisual
● Zoomdata (via the cloud platforms)
● RAW
● Datawrapper

27
Online Data Visualization Software
Got from Coursera course on Data Visualization

● Tableau
● SAP Lumira (including a free Personal Edition version)
● Microsoft Excel (or any other spreadsheet that includes charts)
● ClearStory
● Mathematica
● MATLAB
● MatPlotLib (if you are comfortable programming Python)
● R Programming Language
● ggplot2

28
The 7 Best Data Visualization Tools Available Today
● Tableau
● Qlikview
● FusionCharts
● Highcharts
● Datawrapper
● Plotly
● Sisense
● Google Charts

29
Tableau
● Tableau is often regarded as the grand master of data visualization software.
● Tableau has a very large customer base of 57,000+ accounts across many
industries
● Due to its simplicity of use and ability to produce interactive visualizations far
beyond those provided by general BI solutions.
● It is particularly well suited to handling the huge and very fast-changing datasets
which are used in Big Data operations, including artificial intelligence and
machine learning applications

30
Qlikview
● Qlik with their Qlikview tool is the other major player in this space and Tableau’s
biggest competitor.
● The vendor has over 40,000 customer accounts across over 100 countries
● Its highly customizable setup and wide feature range are a key advantage.
● This however can mean that it takes more time to get to grips with and use it to
its full potential.
● In addition to it offers powerful business intelligence, analytics and enterprise
reporting capabilities and has clean and clutter-free user interface.
● Qlikview is commonly used alongside its sister package, Qliksense, which
handles data exploration and discovery.
● There is also a strong community and there are plenty of third-party resources
available online to help new users understand how to integrate it in their
projects. 31
FusionCharts
● This is a very widely-used, JavaScript-based charting and visualization package
in the paid-for market.
● It can produce 90 different chart types and integrates with a large number of
platforms and frameworks giving a great deal of flexibility.
● One feature that has helped make FusionCharts very popular is that rather than
having to start each new visualization from scratch, users can pick from a range
of “live” example templates, simply plugging in their own data sources as needed.

32
Highcharts
● Like FusionCharts this also requires a licence for commercial use, although it can
be used freely as a trial, non-commercial or for personal use.
● Its website claims that it is used by 72 of the world’s 100 largest companies
● It is often chosen when a fast and flexible solution must be rolled out, with a
minimum need for specialist data visualization training before it can be put to
work. A key to its success has been its focus on cross-browser support, meaning
anyone can view and run its interactive visualizations, which is not always true
with newer platforms.

33
Datawrapper
● Datawrapper is increasingly becoming a popular choice, particularly among
media organizations which frequently use it to create charts and present
statistics.
● It has a simple, clear interface that makes it very easy to upload csv data and
create straightforward charts, and also maps, that can quickly be embedded into
reports.

34
Plotly
● Plotly enables more complex and sophisticated visualizations
● Its integration with analytics-oriented programming languages such as Python, R
and Matlab.
● It is built on top of the open source d3.js visualization libraries for JavaScript, but
this commercial package (with a free non-commercial licence available) adds
layers of user-friendliness and support as well as inbuilt support for APIs such as
Salesforce.

35
Sisense
● Sisense provides a full stack analytics platform but its visualization capabilities
provide a simple-to-use drag and drop interface which allow charts and more
complex graphics, as well as interactive visualizations, to be created with a
minimum of hassle.
● It enables multiple sources of data to be gathered into one easily accessed
repositories where it can be queried through dashboards instantaneously, even
across Big Data-sized sets.
● Dashboards can then be shared across organizations ensuring even non
technically-minded staff can find the answers they need to their problems.

36
Google Charts
● Google is one of the top trendsetters in big data.
● The company has designed Google Charts, a JavaScript charting library that
enhances web apps by incorporating interactive charting ability.
● You can build a variety of charts on Google Charts, including bar charts, area
charts, line charts, pie charts, spline charts, etc.
● The chart options are numerous, and you can personalize them to present your
data in the best way.
● They range from simple to complex charts.
● In addition, charts made using this tool come in HTML5 and SVG formats. They
can, therefore, be viewed on any device or browser.

37
Keys factors of Data Visualization
● (Control of Presentation, Faster and Better JavaScript processing, Rise of HTML5,
Lowering the implementation Bar)
● HTML5 started

38
Control of presentation

39
What Technology brings to the table
● Web professionals are dependent on robust web software to accomplish any
aspect of their work, but the need for power tools is particularly vital to properly
handle data visualization. Following three are the keys to represent the data.
○ Faster, more efficient JavaScript engines in browsers
○ The rapid HTML5 compatible browsers
○ The increased availability of JavaScript frameworks and libraries

40
Faster and Better JavaScript processing
● For the last several years, browser makers have identified JavaScript processing
as a key battleground and have pursued faster JavaScript engines with great
vigor (शि त)

41
Faster and Better JavaScript processing
● The bar graph in
figure compares runs
of the sunspider
benchmark created
and maintained by
webkit.org for older
browsers against
latest.
● The lesser values
indicate faster and
more desirable
processing times by
JavaScript Engines.
42
Faster and Better JavaScript processing
● The increase in Javascript processing functionality has direct effect on both the
data analysis and rendering phase of data visualization.
● JS engines handles raw numeric computations as well as on-screen drawing.
● It greatly increases the viability of direct browser data visualization without
restoring to a third party plug-in like adobe flash.

43
Rise of HTML5
● A faster engine isn’t much good without fuel to run it.
● Luckily a load of high-octane HTML5 was delivered just in time.
● The roots of HTML5 can be found in 2004, and the Web Hypertext Application
Technology(WHAT) working group -but adoption was slow.
● W3C had slated the web language for final recommendation status in 2022.
● The introduction of smart phones notably Apple’s iPhone, changed all that.
● The device’s embrace of HTML5 in instead of Flash triggered a feature adoption
race among all major browsers.
● HTML5 becoming the current standard for mobile devices.

44
Rise of HTML5
● What HTML5 so important to data visualization ?
● This latest version of web’s primary language brings along two closely knit
partners: CSS3 and advanced Javascript APIs.
● The enhanced capabilities brought by these three related technologies have truly
revolutionized web design and development overall.

45
Rise of HTML5
● The key features of HTML5 that have been especially beneficial for data
visualization are:
○ The <canvas> tag: Include a seemingly blank <canvas> element on your HTML5 page and
suddenly you have access to the full palette of graphics- including primitives(such as circles and
rectangles, plotted points with connected lines, gradients, text, imported images, and much more-
all drawn by JavaScript, live. You have an option to make whatever you put on your canvas
interactive, capable of being changed by the user.

46
Rise of HTML5

47
Lowering the implementation bar
● Now we have powerful vehicle i.e. Javascript engine and super fuel i.e. HTML5.
But who drives?
● Javascript related libraries specifically those written in jQuery.
● Though with Javascript knowledge the requisite data acquisition, conversation
and rendering can be managed. However, armed with core jQuery and targeted
libraries such a process becomes more efficient and successful.
● Most sophisticated Javascript libraries also make it more straightforward to
modify controlling parameters and even the data itself, all on the fly. These added
degree of flexibility strengthens the case for taking advantage of code libraries as
such Google Charts, D3, Raphel and jqPlot to name.

48
Exploring the Visual Data Spectrum

● Choose the right representation for your data is required.


● Go with the building blocks, such as a pie of bar chart, or opt for more
sophisticated conveyance, such as a timeline-based infographics, depends on
many factors.
● To ensure the correct selection, understanding of full range of choices is
required.
● So let’s know the charting primitives.

49
Charting primitives
● Graphics artists refer to core elements such as lines, rectangles and ovals as
drawing primitives.
● We borrow the concept, applied it to data visualizations, and named it as
charting primitives.
● In this collection, most familiar members of visualizations family too are
included: i.e. plotted points, line charts, bar charts, pie charts and area charts.
● Many options are design oriented-such as 2D versus 3D- others are crucial for
representing sophisticated data in a meaningful way.

50
(Data Points, Line Charts, Bar Charts, Pie Charts, Area
Charts)

51
Data Points
● Data point is the most basic of the charting primitives.
● A data point is a single element plotted on a graph, via the X and Y axes.
● So, data point charts are also known as XY charts.
● As they appear as dots scattered across the plane, they are referred to as scatter
charts too.

52
Data Points
● The graph
represents
the
interconnecti
on between X
and Y data,
i.e.
correlation.

Fig: Data points are plotted for X and Y values 53


Data Points
● The correlation is of 3 types:
○ Positive correlation
○ Negative correlation
○ No relation
● If X and Y both increases together - Positive correlation
● If X increases and Y decreases - Negative correlation
● If X increases, can’t say certainly that Y will increase or decrease, is No
correlation.
● I.e. Data points on graph appears random, without any discernable pattern,
we can say No correlation is there.
● If there is one - to -one correspondence between X and Y, the correlation is
perfect.

54
Line charts
● When data points are connected with a continuous line, it is a line chart.
● Line charts are the most common and form the basis for other types of charts:
area, stacked line, and curve fit.
● A single data series is rendered as one line moving from point to point.

55
Line charts
● In line charts, markers are used
to show data points.
● Stock price is typically presented
using line chart.
● Day to day change and
percentage change from the
median over a set of period is
typically presented using line
chart.

56
Line charts
● Stock prices like the percentage
variations for Apple are
represented using line chart.

57
Line charts
● Comparing data sets
with same unit of
measure

58
Bar charts
● A bar chart or bar graph is a chart or graph that presents categorical data with
rectangular bars with heights or lengths proportional to the values that they
represent. The bars can be plotted vertically or horizontally. A vertical bar chart
is sometimes called a column chart.

59
Column chart
● A vertical bar chart is called a column chart.

60
Pie charts
● A pie chart is a type of graph that
represents the data in the
circular graph. The slices of pie
show the relative size of the data.
● It is a type of pictorial
representation of data.
● A pie chart requires a list of
categorical variables and the
numerical variables.

61
Area charts
● An area chart is like a line chart in terms of how data values are plotted on the
chart and connected using line segments.
● In an area chart, however, the area between the line segments and the x-axis is
filled with color.
● An area chart is a good choice when you want to see volume change over a
period of time, without focusing on specific data values. It gives a sense of
summation of the quantitative data.
● Many a times, an area chart combines the line chart and bar chart to show how
one or more groups' numeric values change over the progression of a second
variable, typically that of time.
● An area chart is distinguished from a line chart by the addition of shading
between lines and a baseline, like in a bar chart.
62
Area charts

63
Steps to prepare chart in HTML5 CANVAS
● Step 1 - Preparing the data
● Step 2 - Including JavaScript files
● Step 3 - Creating a chart container
● Step 4 - Creating chart instance and rendering the chart
● Step5 - Customising the design

Official website of canvas Js: https://canvasjs.com/

64
65
66
67
Exploring advanced Visualizations (Candlestick Charts,
Bubble Charts, Surface Charts, Map Charts,
Infographics).

68
Candlestick chart
● A candlestick chart (also called Japanese candlestick chart) is a style of financial
chart used to describe price movements of a security, derivative, or currency.
● Each "candlestick" typically shows one day, thus a one-month chart may show
the 20 trading days as 20 candlesticks.
● Candlestick charts can also be built using intervals shorter or longer than one
day.
● It tends to represent trading patterns over short periods of time, often a few days
or a few trading sessions.

69
Candlestick chart
● It is similar to a bar chart in
that each candlestick
represents all four
important pieces of
information for that day:
open and close in the thick
body; high and low in the
“candle wick”.

70
Candlestick chart

71
Online code link:
https://canvasjs.com/docs/chart
s/chart-types/html5-candle-stick
-chart/

72
Bubble Charts
● A bubble chart is a type of chart that displays three dimensions of data. Each
entity with its triplet (v1, v2, v3) of associated data is plotted as a disk that
expresses two of the vi values through the disk's xy location and the third
through its size.
● Bubble charts can facilitate the understanding of social, economical, medical, and
other scientific relationships.
● Bubble chart is used instead of a scatter chart if your data has three data series
that each contain a set of values. The sizes of the bubbles are determined by the
values in the third data series. Bubble charts are often used to present financial
data.
● Bubble charts can be considered a variation of the scatter plot, in which the data
points are replaced with bubbles.
73
Bubble chart

74
Bubble chart

75
Bubble Chart
● Bubble Chart is having 3 dimensions visualization.
● It is very much similar to Scatter Charts except that size of bubble represents
another parameter.
● Out of the three parameters required (x, y, z), x & y determine the bubble's
position on X & Y Axis & z determines its size.
● One notable behavior of bubble is that z value of data point is proportional to the
area of bubble but not diameter/radius.

76
Online code link:
https://canvasjs.com/docs/chart
s/chart-types/html5-bubble-cha
rt/

77
Surface Charts
● Surface Chart (3D Surface Plot) displays a set of three-dimensional data as a
mesh surface. It is useful when you need to find the optimum combinations
between two sets of data.
● The colors and patterns in Surface Charts indicate the areas that are in the same
range of values by analogy with a topographic map.
● A typical 3D Surface Plot is constructed from three variables: X, Y, and Z. Two of
them are independent, located on the horizontal axes. The other is dependent,
shown along the vertical axis.
● Hence, Surface Charts represent a functional relationship between a designated
dependent variable and two independent ones.

78
Surface Charts

79
Online code link:
https://canvasjs.com/docs/chart
s/chart-types/html5-area-chart/

80
Map Charts
● A map chart is used to show geographical data.
● A map chart with markers is used to display the markers in a geographical or
spatial context. A map chart can also be used to show other than geographical
data.

81
Map chart of India

82
Map Charts
Not supported in HTML5 canvas just now.

83
Infographics
● Infographics are graphic visual representations of information, data, or
knowledge intended to present information quickly and clearly.
● They can improve cognition by utilizing graphics to enhance the human visual
system's ability to see patterns and trends.

84
Infographics of Digital marketting

85
Infographics

86
Making use of HTML5 CANVAS, Integrating SVG

87
SVG
What is SVG?

● SVG stands for Scalable Vector Graphics


● SVG is used to define vector-based graphics for the Web
● SVG defines graphics in XML format
● Each element and attribute in SVG files can be animated
● SVG is a W3C recommendation
● SVG integrates with other standards, such as CSS, DOM, XSL and JavaScript
● SVG graphics are scalable, and do not lose any quality if they are zoomed or
resized.

88
SVG ADVANTAGES
Advantages of using SVG over other image formats (like JPEG and GIF) are:

● SVG images can be created and edited with any text editor
● SVG images can be searched, indexed, scripted, and compressed
● SVG images are scalable
● SVG images can be printed with high quality at any resolution
● SVG images are zoomable
● SVG graphics do NOT lose any quality if they are zoomed or resized
● SVG is an open standard
● SVG files are pure XML

89
SVG Shapes
SVG has some predefined shape elements that can be used by
developers:

● Rectangle <rect>
● Circle <circle>
● Ellipse <ellipse>
● Line <line>
● Polyline <polyline>
● Polygon <polygon>
● Path <path>

90
91
Code explanation:

● The width and height attributes of the <rect> element define the height and the width of the rectangle
● The x and y attributes defines the x- and y-position of the top-left corner of the rectangle (x="10" places the rectangle 10px from
the left margin and y="10" places the rectangle 10px from the top margin) in the SVG canvas
● The rx and ry attributes defines the radius of the corners of the rectangle
● The fill attribute defines the fill color of the rectangle

92
Code explanation:

● The style attribute is used to define CSS properties for the rectangle
● The CSS fill property defines the fill color of the rectangle
● The CSS stroke-width property defines the width of the border of the rectangle
● The CSS stroke property defines the color of the border of the rectangle

93
94
Code explanation:

● The r attribute defines the radius of the circle


● The cx and cy attributes define the x- and y-axes center of the circle. If they are
omitted, the circle's center is set to (0,0)
● The fill attribute defines the color of the circle

95
Code explanation:

● The stroke attribute defines the color of the border around the
circle
● The stroke-width attribute defines the width of the border
around the circle

96
Code explanation:

● The opacity attribute defines the opacity of the circle

97
98
Code explanation:

● The rx attribute defines the x (horizontal) radius


● The ry attribute defines the y (vertical) radius
● The cx attribute defines the x-axis center of the ellipse
● The cy attribute defines the y-axis center of the ellipse

99
100
101
Code explanation:

● The <x1> and <y1> attributes define the start of the line (0,0)
● The <x2> and <y2> attributes define the end of the line (300,200)

102
103
104
105
106
107
Code explanation:

● The points attribute defines the list of points (pairs of x and y coordinates)
required to draw the polyline

108
SVG Animation
SVG Animation
SVG elements can be animated.

In SVG, we have four animation elements which sets or animates SVG graphics:

● <set>
● <animate>
● <animateTransform>
● <animateMotion>

109
SVG Animation
SVG <set>
The <set> element sets the value of an attribute for a specified duration.

In this example, we create a red circle that starts with a radius of 25, then after 3 seconds the radius will be set to 50:

Code explanation:

● The attributeName attribute in the <set> element defines which attribute to change
● The to attribute in the <set> element defines the new value for the attribute 110
● The begin attribute in the <set> element defines when the animation should start
SVG Animation
SVG <animate>
The <animate> element animates an attribute of an element.

The <animate> element should be nested inside the target element.

In this example, we create a red circle. We animate the cx attribute from 50 to 90%. This means that the circle will go from left to right:

111
SVG Animation

Code explanation:

● The attributeName attribute defines which attribute to animate


● The begin attribute defines when the animation should start
● The dur attribute defines the duration of the animation
● The from attribute defines the starting value
● The to attribute defines the ending value
● The repeatCount attribute defines how many times the animation should play 112
SVG Animation
SVG <animate> with Freeze
In this example, we want the red circle to freeze (stop) when it comes to its final position (instead of snapping back to the start
position):

Code explanation:

● The fill="freeze" attribute defines that the animation should freeze when it comes to its final position 113
SVG Animation
SVG <animateTransform>
The <animateTransform> element animates the transform attribute on the target element.

The <animateTransform> element should be nested inside the target element.

In this example, we create a red rectangle that will rotate:

114
SVG Animation

● he attributeName attribute animates the transform attribute of the <rect> element


● The begin attribute defines when the animation should start
● The dur attribute defines the duration of the animation
● The type attribute defines the type of transformation
● The from attribute defines the starting value
● The to attribute defines the ending value
115
● The repeatCount attribute defines how many times the animation should play
HTML Canvas
The HTML <canvas> element is used to draw graphics on a web page.

The HTML <canvas> element is only a container for graphics. You must use a script to actually draw the
graphics.

Canvas has several methods for drawing paths, boxes, circles, text, and adding images.

Canvas is supported by all major browsers.

What is HTML Canvas?


The HTML <canvas> element is used to draw graphics, on the fly, via scripting (usually
JavaScript).

The <canvas> element is only a container for graphics. You must use a script to actually
draw the graphics.

Canvas has several methods for drawing paths, boxes, circles, text, and adding images.

116
Canvas Example
In HTML, a <canvas> element looks like this:

<canvas id="myCanvas" width="200" height="100"></canvas>

The id attribute is required (so it can be referred to by JavaScript).

The width and height attribute defines the size of the canvas.

Tip: The default size of the canvas is 300px (width) x 150px (height).

Tip: You can have multiple <canvas> elements on one HTML page.

By default, the <canvas> element has no border and no content.

To add a border, use a style attribute:

117
Step 1: Find the Canvas Element
First of all, you must find the <canvas> element. You access a <canvas> element with the HTML DOM method
getElementById():

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

Step 2: Create a Drawing Object


Secondly, you need a drawing object for the canvas. The getContext() method returns an object with tools (properties
and methods) for drawing:

const ctx = canvas.getContext("2d");

Step 3: Draw on the Canvas


Finally, you can draw on the canvas. Set the fill-color to red with the fillStyle property:

ctx.fillStyle = "red";

The fillStyle property can be a color, a gradient, or a pattern. The default fillStyle is black.

The fillRect(x, y, width, height) method draws the rectangle, filled with the fill style color, on the canvas:
118
ctx.fillRect(0, 0, 150, 75);
119
120
121
122
123
124
125
126
127
Canvas Animation

128
The basis of SVG Canvas

comparison

Definition It is an XML based vector image format It is an element in HTML to draw graphics

for interactivity. on web pages.

Format It uses a vector image format. It uses the bitmap image format.

Flexible SVGs are more flexible as we can Canvas images are not that flexible.

expand the size beyond their natural

129
The basis of SVG Canvas

comparison

Event Handlers It provides any support for event It does not provide support for event

handlers. handlers.

Gaming It does not suit for any gaming These are well suited for gaming

application. applications

Program SVG refers to draw the program. Canvas refers to paint the program.

130

You might also like