Professional Documents
Culture Documents
Canvas :
To draw a straight line on a canvas, use the following methods:
moveTo(x,y) - defines the starting point of the line
lineTo(x,y) - defines the ending point of the line
To actually draw the line, you must use one of the "ink" methods, like stroke().
setLineDash([ ]) : Sets the pattern for drawing dashed lines. The argument that you give to the
function should be an array that contains numbers that indicate the desired dash setting that includes
tha length of ths dash and gap between two dash.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="2000" height="1000" style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.moveTo(50,50);
ctx.lineTo(200,100);
ctx.stroke();
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="2000" height="1000" style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.setLineDash([5]); //To draw Dashed Line
ctx.moveTo(50,50);
ctx.lineTo(200,100);
ctx.stroke();
</script>
</body>
</html>
To draw a rectangle on a canvas, use the following methods:
strokeRect(): draws a rectangle (no fill). The default color of the stroke is black. Use the
strokeStyle property to set a color, gradient, or pattern to style the stroke.
Syntax: context.strokeRect(x,y,width,height);
fillRect(): method draws a "filled" rectangle. The default color of the fill is black. Use the fillStyle
property to set a color, gradient, or pattern used to fill the drawing.
Syntax: context.fillRect(x,y,width,height);
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid black;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
</script>
</body>
</html>
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.
Syntax: context.arc(x, y, r, sAngle, eAngle, counterclockwise);
Where,
x - The x-coordinate of the center of the circle
y - The y-coordinate of the center of the circle
r - The radius of the circle
sAngle - The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle)
eAngle - The ending angle, in radians
counterclockwise - Optional. Specifies whether the drawing should be counterclockwise or
clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// Empty Circle
ctx.beginPath();
ctx.arc(80, 80, 40, 0, 2 *Math.PI);
ctx.strokeStyle="green";
ctx.stroke();
// Filled Circle
ctx.beginPath();
ctx.arc(200, 80, 40, 0, 2*Math.PI);
ctx.fillStyle="blue";
ctx.fill()
// Half Circle
ctx.beginPath();
ctx.arc(300, 80, 40, 0, Math.PI);
ctx.strokeStyle="red";
ctx.stroke();
// 1/4th Part of Circle
ctx.beginPath();
ctx.arc(80, 200, 40, 0, 0.5*Math.PI);
ctx.strokeStyle="magenta";
ctx.stroke();
// 3/4th Part of Circle
ctx.beginPath();
ctx.arc(200, 200, 40, 0, 1.5*Math.PI);
ctx.strokeStyle="green";
ctx.stroke();
</script>
</body>
</html>
The fillText(): method draws filled text on the canvas. The default color of the text is black.
Use the font property to specify font and font size.
Use the fillStyle property to render the text in another color/gradient.
Syntax: context.fillText(text,x,y,maxWidth);
Where,
text - Specifies the text that will be written on the canvas
x - The x coordinate where to start painting the text (relative to the canvas)
y - The y coordinate where to start painting the text (relative to the canvas)
maxWidth - Optional. The maximum allowed width of the text, in pixels
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:10px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:10px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var grd = ctx.createLinearGradient(0,200,200,0);
grd.addColorStop(0, "red");
grd.addColorStop(0.25, "white");
grd.addColorStop(0.5, "gray");
grd.addColorStop(1, "pink");
</script>
</body>
</html>
Transformation of Shapes :
1) Scale:
The scale() method scales the current drawing, bigger or smaller. 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.
<!DOCTYPE HTML>
<html>
<body>
<canvas id="mycanvas" style="border: 1px solid red;" width=380 height=350>
Canvas is not supported
</canvas>
<script type="text/javascript">
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
ctx.strokeStyle= "Grey";
ctx.strokeRect(5, 5, 35, 25);
<!DOCTYPE HTML>
<html>
<body>
<h2>Advanced Shapes</h2>
<canvas id="mycanvas" style="border: 1px solid red;" width=380 height=350>
Canvas is not supported
</canvas>
<script type="text/javascript">
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle="grey";
ctx.fillRect(10, 10, 100, 50);
ctx.translate(70, 70);
ctx.fillStyle="pink";
ctx.fillRect(10, 10, 100, 50);
</script>
</body>
</html>
3. Rotate:
The rotate() method rotates the current drawing.
The rotation will only affect drawings made AFTER the rotation is done.
Syntax: context.rotate(angle);
Where, angle - The rotation angle, in radians.
To calculate from degrees to radians: degrees*Math.PI/180.
Example: to rotate 5 degrees, specify the following: 5*Math.PI/180
<!DOCTYPE HTML>
<html>
<body>
<h2>Advanced Shapes</h2>
<canvas id="mycanvas" style="border: 1px solid red;" width=380 height=350>
Canvas is not supported
</canvas>
<script type="text/javascript">
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
2. clearInterval();
The global clearInterval() method cancels a timed, repeating action which was previously
established by a call to setInterval().
Syntax: clearInterval(intervalID);
3. setTimeout():
This method executes the supplied code only once after a given time milliseconds.
Syntax: setTimeout(callback, time);
4. requestAnimationFrame():
This 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.
Syntax: requestAnimationFrame(callback);
Rectangle Animation
<!DOCTYPE HTML>
<html>
<body>
<canvas id="mycanvas" style="border: 1px solid red;" width=380 height=350>
Canvas is not supported
</canvas>
<script type="text/javascript">
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
var startX = 10;
var startY = 10;
var width = height = 50;
var endX = canvas.width - width;
var x = startX;
var y = startY;
var step = 0;
function logic ()
{
step += 0.02;
x = lerp(startX, endX, step);
if (x < endX)
requestAnimationFrame(draw);
}
function draw()
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#ff0000";
ctx.fillRect(x, y, width, height);
}
requestAnimationFrame(draw);
setInterval(logic, 1000/60);
</script>
</body>
</html>
Circle Animation
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width='300px' height='300px'/>
<script type='text/javascript'>
var canvas= document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
function drawCircle()
{
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(cx, cy, radius, 0, newAngle * Math.PI);
ctx.stroke();
};
function go()
{
// Sincle Maximum angle is 2*PI, we use 2 for 200 divisions
if (angle < 200)
{
angle = angle + 1;
newAngle = angle *.01;
requestAnimationFrame(drawCircle);
}
}
requestAnimationFrame(drawCircle);
setInterval(go, 1000/60);
</script>
</body>
</html>
CanvasJS :
CanvasJS Charts is an HTML5 charting library that runs across devices and browsers to provide
businesses of any size with a tool to visualize their key data. CanvasJS Charts allows users to create
rich dashboards that work across devices without compromising on maintainability or functionality
of the web application.
<!DOCTYPE HTML>
<html>
<head>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script >
window.onload = function ()
{
var chart = new CanvasJS.Chart("chartContainer",
{
title:{text: "Top Oil Reserves"},
axisX:{title: "Countries"},
axisY:{title: "Reserves(MMbbl)"},
data: [{
type:"column", //bar, doughnut, line, pie
showInLegend:true,
legendText:"MMbbl = one million barrels",
dataPoints: [
{ y: 200878, label: "Venezuela" },
{ y: 196455, label: "Saudi" },
{ y: 179709, label: "Canada" },
{ y: 168400, label: "Iran" },
{ y: 155798, label: "Iraq" },
{ y: 164398, label: "UAE" }]
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 100%; width: 100%;"></div>
</body>
</html>
Styling and Animation of Column Chart_CanvasJS
Enables Animation while rendering the Chart.
animationEnabled Options: true or false
animationDuration Sets the duration of animation in milliseconds.
Sets the theme of the Chart. Various predefined themes
theme are bundled along with the library.
Options: “light1″,”light2”, “dark1”, “dark2”
title
text Sets the Title’s text.
Sets the Font Family of Chart Title.
fontFamily
Example: “arial” , “tahoma”, “verdana”
fontColor Sets the font color of Chart Title.
fontSize Sets the font Size of Chart Title in pixels.
fontWeight Options: “lighter”, “normal”, “bold” , “bolder”
padding Allows you to set the padding for Chart Title.
margin Lets you set margin between Title & PlotArea.
Sets the maximum width of title after which it gets
maxWidth wrapped or clipped depending on whether wrap is set
to true (default) or false.
Wrap specifies whether to wrap the title once its width
wrap crosses maxWidth or not. If it is set to false, title gets
clipped after reaching maxWidth.
backgroundColor Sets the background color of Chart Title.
Sets the thickness of border around the Title in pixels.
borderThickness To display border around title, set the borderThickness
to a number greater than zero.
borderColor Sets the color of border around Chart Title.
To display rounded borders around the title, set the
cornerRadius cornerRadius of title. Higher the value, more rounded
are the corners.
Align the Chart Title vertically.
verticalAlign
Options: “top”, “center”, “bottom”
Align the Chart Title horizontally.
horizontalAlign
Options: “left”, “right”, “center”
axisX, axisY
title Sets the Axis Title.
Sets the Font Family of Axis Title.
titleFontFamily
Example: “calibri”, “tahoma, “verdana” ..
titleFontColor Sets the Font Color of Axis Title
titleFontSize Sets the Font Size of Axis Title in pixels.
Sets the Font Weight used in the Axis Title.
titleFontWeight
Options: “lighter”, “normal”, “bold” , “bolder”
labelFontFamily Sets the Font Family of Axis labels.
labelFontColor Sets the Axis Label color.
labelFontSize Sets the Axis Label Font Size in pixels.
Set the font Weight used in Axis Labels.
labelFontWeight
Options: “lighter”, “normal”, “bold” , “bolder”
Sets the text alignment of axis X or Y labels.
labelTextAlign
Options: “left”, “center”, “right”
labelPlacement allows you to position axisX label
labelPlacement either inside or outside the plot-area.
Options: “inside”, “outside”.
Sets the Dash Type for grid lines on axisX.
Options: “solid”, “shortDash”, “shortDot”,
gridDashType “shortDashDot”, “shortDashDotDot”, “dot”, “dash”
“dashDot”, “longDash”, “longDashDot”,
“longDashDotDot”
Sets the Thickness of Grid Lines. To display grid on
gridThickness Axis X, set the Grid Thickness to a number greater than
zero.
Sets the Interlacing Color that alternates between the
interlacedColor set interval. If the interval is not set explicitly, then the
auto calculated interval is considered.
gridColor Sets the Color of Grid Lines.
tickPlacement allows you to position axisX ticks either
tickPlacement inside or outside the plot-area.
Options: “inside”, “outside”.
Sets the length of Tick Marks that are drawn on the
tickLength
Axis.
tickColor Sets the color of Tick Marks drawn on the axis.
prefix A string that prepends all the labels on axis X or Y.
suffix A string that appends all the labels on axis X or Y.
Sets the distance between Tick Marks, Grid Lines and
Interlaced Colors.
interval
Default: Automatically Calculated
Example: 50, 75..
legend
Sets the cursor type for legend items.
cursor
Options: “pointer”, “crosshair” ..
Setting reversed property to true shows legend items in
reversed reverse order.
Options: true or false
Sets the maximum width of legend. If any item is
longer than the maxWidth, it gets wrapped or clipped
maxWidth
depending on the itemWrap property. itemWrap is true
by default.
Sets the maximum height of legend. Once the
maximum height is reached, remaining legend items
are not shown when horizontally stacked (while on top
maxHeight
or bottom or plotArea) and a new column is created
when items are vertically stacked (when displayed to
the left or right of plotArea).
itemWrap specifies whether to wrap or clip legendText
itemWrap
once its width crosses itemMaxWidth / maxWidth.
Sets the maximum width of individual legend items
after which they get wrapped or clipped depending on
itemMaxWidth whether itemWrap is set to true (default) or false.
itemMaxWidth can’t be greater than maxWidth of
legend.
Sets the mouseover event handler for the legend, which
itemmouseover is triggered when the user moves the mouse(input
device) over a legend item.
Align the Legend Position vertically.
verticalAlign
Options: “top”, “center”, “bottom”
Align the Legend Position horizontally.
horizontalAlign
Options: “left”, “right”, “center”
Example
<!DOCTYPE HTML>
<html>
<head>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script >
window.onload = function ()
{
var chart = new CanvasJS.Chart("chartContainer",
{
animationEnabled: true,
animationDuration: 2000,
theme: "light1", // "light1", "light2", "dark1", "dark2"
title:{ text: "Olympic Medals",
fontFamily: "arial black",
fontColor: "Red",
fontSize: 30,
fontWeight: "bold",
padding: 10,
margin: 15,
maxWidth: 1000,
wrap:true,
backgroundColor: "Pink",
borderThickness: 5,
borderColor: "Red",
cornerRadius: 5,
verticalAlign:"bottom",
horizontalAlign:"center"
},
data: [{
type:"bar", //column, doughnut, line, pie
showInLegend:true,
legendText:"Vegetables",
dataPoints: [
{ x: 1, y: 58},
{ x: 2, y: 69},
{ x: 3, y: 80},
{ x: 4, y: 74}]
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 100%; width: 800px;"></div>
</body>
</html>
Basic Pie Chart_CanvasJS
<!DOCTYPE HTML>
<html>
<head>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script >
window.onload = function ()
{
var chart = new CanvasJS.Chart("chartContainer",
{
title:{text: "Olympic Medals"},
data: [{
type:"pie", //column, bar, doughnut, line
showInLegend:true,
indexLabel: "{name} {y}",
dataPoints: [
{ y: 543, name: "India", exploded: true},
{ y: 336, name: "China" },
{ y: 443, name: "France" },
{ y: 273, name: "Great Britain" },
{ y: 369, name: "Germany" },
{ y: 596, name: "Russia" },
{ y: 618, name: "USA" }]
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 100%; width: 800px;"></div>
</body>
</html>
Google API :
function renderChart() {
var data = google.visualization.arrayToDataTable([
['product', 'Sales', { role: 'annotation' } ],
['Shoes', 40, "40"],
['Hats', 50, "50"],
['Coats', 35, "35"],
['Scarves', 20, "20"]
]);
data.setValue(0, 2, "40");
data.setValue(1, 2, "50");
data.setValue(2, 2, "35");
data.setValue(3, 2, "20");
}
else{
firstData = !firstData;
data.setValue(0, 1, 25);
data.setValue(1, 1, 40);
data.setValue(2, 1, 45);
data.setValue(3, 1, 15);
data.setValue(0, 2, "25");
data.setValue(1, 2, "40");
data.setValue(2, 2, "45");
data.setValue(3, 2, "15");
}
chart.draw(data, options);
};
}
</script>
</head>
<body>
<h1>Google Column Chart Animated</h1>
<div id="chart" style='width: 550px; height: 40%'></div>
<div>
<input id="changeData" type="button" value="Change">
</div>
</body>
</html>
Basic Pie Chart_Google API
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js">
</script>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['product', 'Sales'],
['Shoes', 40],
['Hats', 50],
['Coats', 35],
['Scarves', 20] ]);
var options = { title : "Product Sales",
pieHole: 0.4,
pieStartAngle: 90,
//is3D: true };
var chart = new
google.visualization.PieChart(document.getElementById("chart"));
chart.draw(data,options);
}
</script>
</head>
<body>
<h1>Google API Bar Chart</h1>
<div id="chart" style="width:500px;height:100%;margin:0"></div>
</body>
</html>
SVG: