0% found this document useful (0 votes)
73 views80 pages

DV Unit-3 PPT

The HTML5 <canvas> element allows for dynamic drawing on a web page via JavaScript. It provides a basic 2D rendering context to draw graphics like lines, rectangles, circles, text, and images. A canvas is a rectangular area defined by a <canvas> tag that has no default content - JavaScript must be used to draw graphics. Common methods for basic shapes include fillRect(), strokeRect(), arc(), and fillText(). Additional features like scaling, rotation, and translation allow transforming canvas drawings. CanvasJS is a JavaScript library that makes it easy to generate interactive charts on HTML5 canvas, supporting a variety of chart types including column, bar, line, area, and pie charts.

Uploaded by

Shaishav Parekh
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)
73 views80 pages

DV Unit-3 PPT

The HTML5 <canvas> element allows for dynamic drawing on a web page via JavaScript. It provides a basic 2D rendering context to draw graphics like lines, rectangles, circles, text, and images. A canvas is a rectangular area defined by a <canvas> tag that has no default content - JavaScript must be used to draw graphics. Common methods for basic shapes include fillRect(), strokeRect(), arc(), and fillText(). Additional features like scaling, rotation, and translation allow transforming canvas drawings. CanvasJS is a JavaScript library that makes it easy to generate interactive charts on HTML5 canvas, supporting a variety of chart types including column, bar, line, area, and pie charts.

Uploaded by

Shaishav Parekh
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/ 80

What is HTML5 Canvas?

• The HTML <canvas> element is used to draw graphics,


on the fly, via JavaScript.
• The canvas element is only a container for graphics.
• We must use JavaScript to actually draw the graphics.
• Canvas has several methods for drawing paths, boxes,
circles, text and adding images.
• It provides a basic 2D rendering API, which you can use
from JavaScript, for rendering vector graphics and text
into a bitmap and displaying that within an HTML page.
Canvas Example
• A canvas is a rectangular area on an HTML page.
• By default, a canvas has no border and no content.
• Syntax:
• <canvas > </canvas>

• Example:
<canvas id=“myCanvas” width=“200” height=“100”>
</canvas>

We have to specify the id attribute every time to refer in javascript.


Canvas Example
• To view border of a canvas use style attribute with border
property.
• Syntax:
• <canvas > </canvas>

• Example:
<canvas id=“myCanvas” width=“200” height=“100”
style=“ 1px solid black;” >
</canvas>

We have to specify the id attribute every time to refer in javascript.


Java script for Basic Shape
<script type="text/javascript">
function drawCanvas(){
var canvas =document.getElementById(‘myCanvas');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
}
}
</script>

The getContext() function returns the drawing context - which is an


object that has all the drawing properties and functions you use to
draw on the canvas.
Basic Elements of Canvas
• Line
• Rectangle
• Circle
• Text
Basic Elements: Line
Begin a path, move to position 0,0. Create a line to position 300,150:

ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(300, 150);
ctx.stroke();

To set width of a line in pixel: ctx.lineWidth = 10;


Basic Elements: Line
Draw a path, shaped as the letter L:

ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(20, 100);
ctx.lineTo(70, 100);
ctx.stroke();
Basic Elements: Rectangle
Draw a filled rectangle: ctx.fillRect(x, y, width, height);
Tip: Use the fillStyle property to set a color, gradient, or pattern used to fill the
drawing.

Draws a rectangle (no fill): ctx.strokeRect(x, y, width, height);


Tip: Use the strokeStyle property to set a color, gradient, or pattern to style the
stroke.

Clear a rectangle within a given rectangle: ctx.clearRect(x, y, width, height);


The clearRect() method clears the specified pixels within a given rectangle.
Basic Elements: Circle
• arc() method creates an arc/curve (used to create circles, or parts of circles).
• To create a circle with arc(): Set start angle to 0 and end angle to 2*Math.PI.
• Use the stroke() or the fill() method to actually draw the arc on the canvas.

ctx.arc(x, y, r, s_Angle, e_Angle, counterclockwise);


Basic Elements: Text
• The fillText() method draws filled text on the canvas. The default color of the text
is black.
Tip: Use the font property to specify font and font size, and use the fillStyle property
to render the text in another color/gradient.

ctx.fillText(text, x, y);

• The strokeText() method draws text (with no fill) on the canvas. The default color
of the text is black.
Tip: Use the font property to specify font and font size, and use the strokeStyle
property to render the text in another color/gradient.

context.srokeText(text, x, y);
Scaling
• The scale() method scales the current drawing, bigger or smaller.
• Note: If you scale a drawing, all future drawings will also be scaled.
• The positioning will also be scaled. If you scale(2,2); drawings will
be positioned twice as far from the left and top of the canvas as
you specify.
ctx.scale(scalewidth, scaleheight);
ScaleWidth and ScaleHeight (1=100%, 0.5=50%, 2=200%, etc.)

Draw a rectangle, scale to 200%, then draw rectangle again:

ctx.strokeRect(5, 5, 25, 15);


ctx.scale(2, 2);
ctx.strokeRect(5, 5, 25, 15);
Rotation
• The rotate() method rotates the current drawing.
• The rotation will only affect drawings made AFTER the rotation is
done.
ctx.rotate(angle);
• The rotation angle, in radians. To calculate from degrees to
radians: degrees*Math.PI/180. Example: to rotate 5 degrees:
5*Math.PI/180

• Rotate the rectangle 20 degrees:

ctx.rotate(20 * Math.PI / 180);


ctx.fillRect(50, 20, 100, 50);
Translation
• The translate() method remaps the (0,0) position on the canvas.
• When you call a method such as fillRect() after translate(), the
value is added to the x- and y-coordinate values.
ctx.translate(x,y);

Draw a rectangle in position (10,10), set new (0,0) position to (70,70).


Draw same rectangle again (notice that the rectangle now starts in
position (80,80):

ctx.fillRect(10, 10, 100, 50);


ctx.translate(70, 70);
ctx.fillRect(10, 10, 100, 50);
CanvasJS
CanvasJS is a powerful and light weight Charting Library built on top of HTML5
& JavaScript. Here are the Key Features of CanvasJS.

• Elegant looking Charts • Animations


• Light Weight • Beautiful Themes
• High Performance • Custom Color Sets
• Runs on Chrome, Firefox, Safari, IE8+ • Localization
• Tablet and Mobile Ready • Number & date Formatting Themes
• Wide range of Customizable Charts • Syncing charts
• Dynamic / Real-time Charts • Axis
• Zooming
• Panning
• Export as Image – JPEG / PNG / Print
CanvasJS
It runs across devices including iPhone, iPad, Android, Microsoft Surface,
Desktops, etc. This allows you to create Rich Dashboards that work across devices
without compromising on Maintainability or Functionality.

• Very simple and intuitive API – you can get started in minutes.
• Comes with Beautiful and Elegant looking themes.
• High performance.
• Works on all modern devices.
• CanvasJS is Standalone – does not depend on any other library.
• Fanatic Support from developers.
HTML5 Canvas Basics
• Download canvasjs.min.js from https://canvasjs.com/fdm/chart
• Extract the downloaded file and put the content in the same folder
as the html file.
Adding CanvasJS to Your Web Pages
• Include the canvasjs.min.js file inside the tag of your web page.

<head>
<script type="text/javascript" src = "canvasjs.min.js">
</script>
</head>
Column Chart with CanvasJS
• Column charts are rectangular bars with lengths proportional to
the values that they represent. A column chart is useful to compare
dataPoints in one or more dataSeries.

• In column charts, axisX is the horizontal Axis and axisY is the


vertical Axis.
Column Chart with CanvasJS
var chart = new CanvasJS.Chart("chartContainer",{});
chart.render();
Column Chart with CanvasJS
var chart = new CanvasJS.Chart("chartContainer",{

});
chart.render();
Column Chart with CanvasJS
var chart = new CanvasJS.Chart("chartContainer",{
title:{
text: “Title of Column Chart" //**Change the title here
},

});
chart.render();
Column Chart with CanvasJS
var chart = new CanvasJS.Chart("chartContainer",{
title:{
text: “Title of Column Chart" //**Change the title here
},
Other Code here
});
chart.render();
Column Chart with CanvasJS
var chart = new CanvasJS.Chart("chartContainer",{
title:{
text: “Title of Column Chart" //**Change the title here
},
data: [ …]
});
chart.render();
Column Chart with CanvasJS
var chart = new CanvasJS.Chart("chartContainer",{
title:{
text: “Title of Column Chart" //**Change the title here
},
data: [

]
});
chart.render();
Column Chart with CanvasJS
var chart = new CanvasJS.Chart("chartContainer",{
title:{
text: “Title of Column Chart" //**Change the title here
},
data: [
{

}
]
});
chart.render();
Column Chart with CanvasJS
var chart = new CanvasJS.Chart("chartContainer",{
title:{
text: “Title of Column Chart" //**Change the title here
},
data: [
{ type: "column",
dataPoints: [..]
}
]
});
chart.render();
Column Chart with CanvasJS
var chart = new CanvasJS.Chart("chartContainer",{
title:{
text: “Title of Column Chart" //**Change the title here
},
data: [
{ type: "column",
dataPoints: [

]
}
]
});
chart.render();
Column Chart with CanvasJS
dataPoints: [
{ x: 10, y: 71 },
{ x: 20, y: 55},
{ x: 30, y: 50 },
{ x: 40, y: 65 },
{ x: 50, y: 95 },
{ x: 60, y: 68 },
{ x: 70, y: 28 },
{ x: 80, y: 34 },
{ x: 90, y: 14}
]
Column chart Using CanvasJS
Putting all together…
… In a web page
A Simple Column Char t
<!DOCTYPE HTML>
<html>
<head>
<script type=“text/javascript” src=“canvasjs.min.js”>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text:“Simple Column Chart"
},
Charts using Canvas: A Simple Column Chart

data: [
{
type: "column", //change type to bar, line, area, pie, etc
dataPoints: [
{ x: 10, y: 71 },
{ x: 20, y: 55},
{ x: 30, y: 50 },
{ x: 40, y: 65 },
{ x: 50, y: 95 },
{ x: 60, y: 68 },
{ x: 70, y: 28 },
{ x: 80, y: 34 },
{ x: 90, y: 14} ] }
] });
Charts using Canvas: A Simple Column Chart

chart.render();
}
</script>
<script type="text/javascript" src="canvasjs.min.js"></script></head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
Output
Other charts: bar, line, area, pie
Just by changing type in the previous code, e.g.
type: "column“ //change type to bar, line, area, pie etc
We can draw different types of charts
Other charts: bar, line, area, pie
Just by changing type in the previous code, e.g.
type: "column“ //change type to bar, line, area, pie etc
We can draw different types of charts
Outline
Customizing HTML5 Canvas Chart

• Labels
• Titles
• Animation
• Theme and multiple series data
Column Chart Customization
• You can set data and all the attributes/properties of a
chart using chart option object.

• You can pass the chart “options” as a constructor


parameter while creating the Chart object
Labels in Chart
• Labels appears next to the dataPoint on axis Line.
• On Axis Y it is the Y value, and on X axis is either user defined “label” or x
value at that point.
• Labels can be customized by using properties.
Labels in Chart
data: [
{
type: "column",
dataPoints: [
{ y: 10, label: "Apples" },
{ y: 15, label: "Mangos" },
{ y: 25, label: "Oranges" },
{ y: 30, label: "Grapes" },
{ y: 28, label: "Bananas" }
]
}
]
Labels in Chart
title: {
text: "Understanding Labels"
},
axisY: {
labelFontSize: 20,
labelFontColor: "dimGrey"
},
axisX: {
labelAngle: -30
},
data: [
{
type: "column",
dataPoints: [
{ y: 10, label: "Apples" },
{ y: 15, label: "Mangos" },
{ y: 25, label: "Oranges" },
{ y: 30, label: "Grapes" },
{ y: 28, label: "Bananas" }
]
}
]
Value Formatting :Labels in Chart
title: {
text: "Understanding Labels"
},
axisY: {
labelFontSize: 20,
labelFontColor: "dimGrey“,
prefix: "$“,
title: "Price per 10Kgs"
},
axisX: {
labelAngle: -30,
title: "Fruits"
},
data: [
{
type: "column",
dataPoints: [
{ y: 10, label: "Apples" },
{ y: 15, label: "Mangos" },
{ y: 25, label: "Oranges" },
{ y: 30, label: "Grapes" },
{ y: 28, label: "Bananas" }
]
Value Formatting :Labels in Chart
dataPoints: [
{ y: 10, label: "Apples" },
{ y: 15, label: "Mangos" },
{ y: 25, label: "Oranges" },
{ y: 30, label: "Grapes“, indexLabel:"Best Seller",
indexLabelFontColor:"red", indexLabelOrientation:
"horizontal", indexLabelPlacement: "inside" },
{ y: 28, label: "Bananas" }
]
}
]
Titles in Chart
title:{
text: "Styling the Title",
fontColor: "#2f4f4f",
fontSize: 30,
padding: 10,
margin: 15,
backgroundColor: "#FFFFE0",
borderThickness: 1,
cornerRadius: 5,
fontWeight: "bold"
}
Titles in Chart
title:{
text: "Styling the Title",
fontColor: "#2f4f4f",
fontSize: 30,
padding: 10,
margin: 15,
backgroundColor: "#FFFFE0",
borderThickness: 1,
cornerRadius: 5,
fontWeight: "bold“,
verticalAlign: "bottom", // "top", "center", "bottom"
horizontalAlign: "left" //right, center
}
Attributes in Chart
Attributes Type Default Options Remarks
interactivityEnabled Boolean true true, false Enables / Disables Chart interactivity like toolTip,
mouse and touch events
animationEnabled Boolean false true, false Enables Animation while rendering the Chart
animationDuration Number 1200 1000, 500, etc Sets the duration of animation in milliseconds
String “light1” “light1″,”light2”.. –
theme
backgroundColor String “#FFFFF “yellow”,
F” “#F5DEB3″..
Multiple series Data
• Now, if you want to say compare sales of various fruits in first and second
quarter of the year, you need to add one more dataSeries (with second
quarter values) to the data array.
Sales in first Sales in second
Quarter Quarter
Fruit (dollars) (dollars)
Banana 58 63
Orange 69 73
Apple 80 88
Mango 74 77
Grape 64 60
Multiple series Data
data: [ //array of dataSeries
{ //dataSeries - second quarter
{ //dataSeries - first quarter
type: "column",
type: "column",
name: "Second Quarter",
name: "First Quarter",
dataPoints: [
dataPoints: [
{ label: "banana", y: 63 },
{ label: "banana", y: 58 },
{ label: "orange", y: 73 },
{ label: "orange", y: 69 },
{ label: "apple", y: 88 },
{ label: "apple", y: 80 },
{ label: "mango", y: 77 },
{ label: "mango", y: 74 },
{ label: "grape", y: 60 }
{ label: "grape", y: 64 }
]
]
}
},
]
Linear Interpolation
• If the two known points are given by the
coordinates (x0, y0) and (x1, y1), the linear
interpolant is the straight line between these
points.

• For a value x in the interval (x0, y0) and (x1, y1),


the value y along the straight line is given from the
equation

𝑦 − 𝑦0 𝑦1 − 𝑦0
=
𝑥 − 𝑥0 𝑥1 − 𝑥0

𝑥 − 𝑥0
𝑦 = 𝑦0 + (𝑦1 −𝑦0 ) ∗
𝑥1 − 𝑥0
Linear Interpolation
𝑥−𝑥0
• is that it resolves to a value between 0
𝑥1 −𝑥0
and 1 depending on how far x is between x0
and x1.

• It acts as a weighting that you can multiply by


the y range (y1 - y0)

𝑥 − 𝑥0
𝑦 = 𝑦0 + (𝑦1 −𝑦0 ) ∗
𝑥1 − 𝑥0
Linear Interpolation in Animation
𝐿𝑖𝑛𝑒𝑎𝑟 𝑖𝑛𝑡𝑒𝑟𝑝𝑜𝑙𝑎𝑡𝑖𝑜𝑛𝑠 𝑎𝑟𝑒 𝑢𝑠𝑒𝑓𝑢𝑙 𝑓𝑜𝑟 𝑐𝑜𝑛𝑛𝑒𝑐𝑡𝑖𝑛𝑔 𝑝𝑜𝑖𝑛𝑡𝑠 𝑤𝑖𝑡ℎ 𝑙𝑖𝑛𝑒 𝑠𝑒𝑔𝑚𝑒𝑛𝑡𝑠,
𝑏𝑢𝑡 𝑡ℎ𝑎𝑡′𝑠 𝑛𝑜𝑡 𝑎𝑙𝑙 𝑦𝑜𝑢 𝑢𝑠𝑒 𝑡ℎ𝑒𝑚 𝑓𝑜𝑟.
𝑥 − 𝑥0
𝑦 = 𝑦0 + (𝑦1 −𝑦0 ) ∗
𝑥1 − 𝑥0
• They are also very useful for moving/blending.
Linear Interpolation in Animation
• If you want a linear animated move between two values based on a time
value that varies between 0 and 1, you can express it with the following
equation:

n = start + (end - start) * speed

• where speed is the time value/move step/blend step,


• start is the start value to move from,
• and end is the end value to move to.
Animating Rectangle
Animating Rectangle
Code & Output:
Method: requestAnimationFrame()
• The requestAnimationFrame() method tells the browser that you wish to
perform an animation and requests that the browser calls a specified
function to update an animation before the next repaint.

• The method takes a callback as an argument to be invoked before the


repaint.

requestAnimationFrame(draw);
setInterval(logic, 1000/60);
Method: setInterval()
The setInterval() method calls a function at specified intervals
(in milliseconds).

setInterval(function, milliseconds);

• 1000/60 is used to call a function 60 times


in 1 second.
• Function to update x, y (starting point of
rectangle) is written in function logic()
• Hence setInterval() call defined in following
way:

setInterval(logic,1000/60);
Animating Circle
Linear Interpolation
• If the two known points are given by the
coordinates (x0, y0) and (x1, y1), the linear
interpolant is the straight line between these
points.

• For a value x in the interval (x0, y0) and (x1, y1),


the value y along the straight line is given from the
equation

𝑦 − 𝑦0 𝑦1 − 𝑦0
=
𝑥 − 𝑥0 𝑥1 − 𝑥0

𝑥 − 𝑥0
𝑦 = 𝑦0 + (𝑦1 −𝑦0 ) ∗
𝑥1 − 𝑥0
Linear Interpolation
𝑥−𝑥0
• is that it resolves to a value between 0
𝑥1 −𝑥0
and 1 depending on how far x is between x0
and x1.

• It acts as a weighting that you can multiply by


the y range (y1 - y0)

𝑥 − 𝑥0
𝑦 = 𝑦0 + (𝑦1 −𝑦0 ) ∗
𝑥1 − 𝑥0
Linear Interpolation in Animation
𝐿𝑖𝑛𝑒𝑎𝑟 𝑖𝑛𝑡𝑒𝑟𝑝𝑜𝑙𝑎𝑡𝑖𝑜𝑛𝑠 𝑎𝑟𝑒 𝑢𝑠𝑒𝑓𝑢𝑙 𝑓𝑜𝑟 𝑐𝑜𝑛𝑛𝑒𝑐𝑡𝑖𝑛𝑔 𝑝𝑜𝑖𝑛𝑡𝑠 𝑤𝑖𝑡ℎ 𝑙𝑖𝑛𝑒 𝑠𝑒𝑔𝑚𝑒𝑛𝑡𝑠,
𝑏𝑢𝑡 𝑡ℎ𝑎𝑡′𝑠 𝑛𝑜𝑡 𝑎𝑙𝑙 𝑦𝑜𝑢 𝑢𝑠𝑒 𝑡ℎ𝑒𝑚 𝑓𝑜𝑟.
𝑥 − 𝑥0
𝑦 = 𝑦0 + (𝑦1 −𝑦0 ) ∗
𝑥1 − 𝑥0
• They are also very useful for moving/blending.
Linear Interpolation in Animation
• If you want a linear animated move between two values based on a time
value that varies between 0 and 1, you can express it with the following
equation:

n = start + (end - start) * speed

• where speed is the time value/move step/blend step,


• start is the start value to move from,
• and end is the end value to move to.
Animating Rectangle
Animating Rectangle
Code & Output:
Method: requestAnimationFrame()
• The requestAnimationFrame() method tells the browser that you wish to
perform an animation and requests that the browser calls a specified
function to update an animation before the next repaint.

• The method takes a callback as an argument to be invoked before the


repaint.

requestAnimationFrame(draw);
setInterval(logic, 1000/60);
Method: setInterval()
The setInterval() method calls a function at specified intervals
(in milliseconds).

setInterval(function, milliseconds);

• 1000/60 is used to call a function 60 times


in 1 second.
• Function to update x, y (starting point of
rectangle) is written in function logic()
• Hence setInterval() call defined in following
way:

setInterval(logic,1000/60);
Animating Circle
Outline
• Google Chart API Basics
• A Basic Bar Chart
Google Charts Basics
• Google Charts is a pure JavaScript based charting
library to enhance web application by adding
interactive charting capability.
• Google charts provides variety of charts such as :
 Bar Chart
 Pie Chart
 Line Chart
 Spline Chart
 Area Chart
• In order to implement Google Charts we need
knowledge of JavaScript.
Use/ Include: Google Charts
• To use Google Charts Google charts provides Content Delivery Network
(CDN)

• Using CDN
• Include the google charts JavaScript file in the HTML page using
following script.

• Syntax:
<head>
<script src = “https://www.gstatic.com/charts/loader,js”/>
</head>
Loading Using: Google Charts
• Once you have included the loader in your webpage, you can use it to load
the desired library packages by calling a load function.

Syntax:
google.charts.load('current', { packages: [ 'corechart‘ ] } );

• But after you load the library packages, you must wait for them to finish
being loaded before proceeding to use them.
• The way to wait is to set up a callback by calling a setOnLoadCallback
function.
Using: Google Charts
• Steps:
• 1. Include Google charts :
<script src = https://www.gstatic.com/charts/loader.js>
• 2. Load charts :
google.charts.load('current', { packages: [ 'corechart‘ ] } );
• 3. use setCallback:
google.charts.setOnLoadCallback(drawChart);
A Basic Bar Chart
• A bar chart or bar graph is chart or graph that
represent categorical data with rectangular bars.
• The bars can be plotted vertically or horizontally.
• A vertical bar chart is called a column chart.

Vertical Bar Chart Horizontal Bar Chart


A Basic Bar Chart
• Code & Output
A Basic Pie Chart
• A pie chart or circle chart is a circular statistical graph
which is divided into slices to illustrate numerical
proportion.
A Basic Bar Chart
• Code & Output
Animation in Google Chart
• Google charts can animate smoothly in one of two ways, either on
startup when you first draw the chart, or when you redraw a chart
after making a change in data or options.
To Animate on Startup:
1. Set your chart data and options. Be sure to set an animation duration and
easing type.
2. Set animation: {"startup": true} — setting this in your options will cause
your chart to start with series values drawn at the baseline, and animate
out to their final state.
3. Call chart.draw(), passing in your data and options.
To Animate on Startup:
To Animate on Startup:
Code & Output:
To Animate on Change in Data:
1. Start with an already rendered chart.
2. Modify the data table or options.
3. Specify the transition behavior using the animation option.
4. Call chart.draw() on your chart to transition to the new values.
To Animate on Startup:
Code & Output:

You might also like