In this article I will explain with example, how to use and implement HTML5 Canvas Charts using the Chart.js library in AngularJS.
The HTML5 Canvas Charts will be populated from JSON object. This article will illustrate how to create a Pie chart using Chart.js library in AngularJS.
Implement HTML5 Canvas Charts using Chart.js in AngularJS
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The HTML DIV consists of an HTML5 Canvas element which will be used to display the HTML5 Canvas Chart.
A JSON object has been created inside the controller and it consists of the following three arrays.
labels – The labels that will be displayed on the Chart.
data – The data values for populating the Chart.
color – Respective color for each data value.
The HTML5 Canvas element is referenced and is then passed as parameter to the Chart function of the Chart.js library.
The other parameters included:-
type – The type of Chart. In this case it is “pie”.
data – The dataset consisting array of the data values and array the background color values.
labels– The array of the Label values.
options – The additional options of the Chart function. Here only the responsive property is set to False so that Chart becomes Non-responsive.
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js" type="text/javascript"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.fruits = {
labels: ["Mango", "Orange", "Peach"],
data: [20, 40, 55],
color: ["#FEBD01", "#FF8C00", "#FFCBA6"]
};
var ctx = document.getElementById("dvCanvas").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
datasets: [{
data: $scope.fruits.data,
backgroundColor: $scope.fruits.color
}],
labels: $scope.fruits.labels
},
options: {
responsive: false
}
});
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<canvas id="dvCanvas" height="300" width="300"></canvas>
</div>
</body>
</html>
Screenshot
Demo
Downloads