getting started

Basics of Creating HTML5 Charts using CanvasJS

This tutorial teaches you the basics of creating HTML5 Charts using CanvasJS with the help of interactive samples. If you know the basics of JavaScript and HTML, you are good to go. Completing this section should make you familiar with the features that are most commonly used.

Each topic contains explanation and a sample “code” with embedded comments that will let you understand the API better. We encourage you to edit the code as described by those comments and familiarize yourself with the API.

Basic Column Chart

Consider the following tabular data to be rendered in the form of column chart.

Fruit Sales in first Quarter
(thousand dollars)
Banana 18
Orange 29
Apple 40
Mango 34
Grape 24

Below is how a minimal basic Column Chart would look like. Here are important things to remember

  1. Instantiate a new Chart object by sending the ID of div element where the chart is to be rendered. You can also pass DOM element instead of ID
  2. Pass all the Chart related “options” to the constructor as the second parameter.
  3. Call chart.render() method to render the chart

Chart “options” mainly contains 4 important items.

  1. title object with its text property set.
  2. dataPoints – which is an array of all data items to be rendered
  3. dataSeries – parent of dataPoints that also defines type of chart and other series wide options
  4. data – array element which is collection of one or more dataSeries objects. Here we have only one dataSeries.

Checkout the code below – experiment and make yourself familiar with the API.


Though we are going to use Column Charts to learn various concepts, it should be easy to change them into any kind of chart that you wish! Just change the type property of dataSeries to any chart type that you need – bar, area, line, scatter, stackedColum, etc.

Checkout (later) all supported chart types

Try it Yourself by Editing the Code below.

Multi Series Column Chart

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. Below is how it can be done.

Fruit Sales in first Quarter
(thousand dollars)
Sales in second Quarter
(thousand dollars)
Banana 18 23
Orange 29 33
Apple 40 48
Mango 34 37
Grape 24 20
Try it Yourself by Editing the Code below.

Customizing Chart

In the above chart we can do couple of customization to improve the visualization of data like

  1. Show values on y axis with $ as prefix and “K” as suffix. Same on toolTips
  2. Display Legend indicating Q1 and Q2

Adding Prefix & Suffix to values is quite simple. You can do so by adding axisY object with prefix and suffix properties set.

Legend can be displayed by setting showInLegend property in dataSeries to true

Below is how it would look like with above properties set. Intentionally the Title has not been set in Axis X and Axis Y. You can do so by setting the title property of axisY or axisX objects.

Try it Yourself by Editing the Code below.

Changing Chart Theme

CanvasJS comes with built in themes that change the look and feel of charts – like “theme1″, “theme2″, “theme3″.

You change theme by setting theme property of chart option to any of the available themes. Below is an example

Try it Yourself by Editing the Code below.

Alternate way of setting / updating data

Above examples show how you can pass data to the constructor while instantiating a chart object. But you can also set these options after creating the object – sometimes it is easier this way.

Options object that you pass to the constructor in the above method can be accessed via options property of chart. Using the same object you can set or update various properties of chart as below.

chart.options.title.text = "Chart Title"; = [array];[0] = {object};[0].dataPoints = [array];
Try it Yourself by Editing the Code below.

  • You should remember to call chart.render() after setting/updating the options – try to batch all updates before calling chart.render()
  • We’ve got the performance part covered! So you can even update the chart every 100 milliseconds (or less if you wish!!) – though such an update rate will not be required in most cases

More Customization

In case you have to do any more customization, below is a table that lists important objects and properties that allow you to do so. Do try out all these options on the above chart.

Customization Object Property
Set Chart Title Size title fontSize – 12,13,14, etc.
Set Chart Title Color title fontColor – red, blue, green, etc
Show Axis Y line axisY lineThickness – 0, 1, 2, etc.
Show value (indexLabels)
on top of Column / Bar
dataSeries indexLabel – “{y}”, “${y}K”, “any text”
Set Axis X label angle axisX labelAngle – 30, 45, 90, etc

Comments 112

  1. Hi Team,

    Many congratulation on achieving this milestone. My query is, how can I load data or provide the input values for graph from a JSON object or a XML file because I will never like to create an array of data and when i speak about data I am referring to many many (dynamic) values generated on various calculation based on my metrics dashboard formulas.

    Rahul Khanna

  2. Pingback: Beautiful HTML5 Charts

    • It is not possible to change the label itself into links. But you can use click event of dataPoint to take user to the corresponding page when clicked.

      In that case you might also want to use “cursor” property of dataSeries/dataPoint to change mouse pointer type.

  3. My requirement is the same as Rahul Khanna, want to see an example that reads a JSON file and the values ​​are plotted. thanks

    • As of now CanvasJS doesn’t have a way to directly plot from the data inside a file. As such you need to read those values and assign the same to the chart.

    • CanvasJS is just a rendering library that draws charts on the client side. Hence you will have to write server side code to connect with any database and use CanvasJS on the client side and it’ll work fine.

  4. In the code I attached the problem is that column 1 and column 3 is not plotted. As if the value of these variables are not considered numeric by CANVASJS. For that reason handle it like this:

    stnetomax var = parseFloat (VPSs [6]);

    but it did not work

    I would appreciate your help.


    window.onload = function() {

    var psañomax = vpss[1];
    var strecibomax = parseFloat(vpss[2]);
    var stimportemax = parseFloat(vpss[3]);
    var stimpmax = parseFloat(vpss[4]);
    var stbonmax = 12385583;
    var stnetomax = parseFloat(vpss[6]);

    var chart = new CanvasJS.Chart(“chartContainer”, {
    title: {
    text: “Concepto:” + psconnom + ” ” + psconnum // SHOW OK

    data: [

    type: “column”,
    name: “Año Mayor ” + psañomax, // SHOW OK
    showInLegend: true,
    dataPoints: [
    { label: “Columna 1 “, y: stimpmax }, // NO SHOW << Here is the problem
    { label: "Columna 2 ", y: stbonmax }, // SHOW OK
    { label: "Columna 3 ", y: stnetomax },// NO SHOW << Here is the problem
    { label: "Columna 4 ", y: 101558923 } // SHOW OK

    • I discovered that I had an error.
      In my code in the object chart I have several DataSeries and only the first DataSeries variables was turning to float with parseFloat. Replace all variables with parseFloat and work.
      It works and looks good!!.

    • Chart requires x & y values to be numbers – enclosing them in quotes creates prolems while doing calculations internally. Glad you figured it out.

  5. Hi Sunil.

    Newbie perspective here for an already great tutorial. The following sentences need to be described (also) in plain English:

    “Above examples show how you can pass data to the constructor while instantiating a chart object. But you can also set these options after creating the object – sometimes it is easier this way. Options object that you pass to the constructor in the above method can be accessed via options property of chart. Using the same object you can set or update various properties of chart as below.”

    What is a constructor?… What is the benefit of the one approach vs the other?… the “easier this way” part?… Easier in what regard?

    Keep up the great work!


  6. Pingback: CanvasJS Charts v1.3 goes GA

  7. Hi is possible change width of existing chart? Do you plan to add some option like conditionaly hide legend depending on width? Parent container follows resize event so i can simply set width/height option.

  8. I pasted the HTML code and tried to open the file in my browser…But the chart is not displayed on the Browser.

    Do I have to make any changes to the code to run in Chrome

    Manoj Shetty

  9. Hey – this looks great. Could you put the initial code somewhere else than in between the tags?

    For example, if I wanted to create a chart within a blog post I may not have access to the , could I put all the code I need within the post itself?


  10. Pingback: AngularJS Charts with CanvasJS | Matt Smith Blog

  11. Mine is basic question how can i run file normally means where to save file with what extension and what libraries i’ll need for execution?

  12. I was unable to give a json format like [{“label”:”First”,”y”:”12″},{“label”:”Second”,”y”:”1″}] in column chart is that a bug or anywere i made mistake in formatting the JSON. But with the same format i can plot pie and doughnut charts. Help me with the issue. Thanking you.

    • Vishnu,

      y value should be a number and not a string. So your json should look like this [{“label”:”First”,”y”:12},{“label”:”Second”,”y”:1}].

  13. Pingback: CanvasJS – jQuery Charts Plugin | Js Plugins

  14. Hi, Do you have any plan to add mouse interaction feature?
    I hope that callback function is called or event triggered with series name and y-axis value when user click on bar or line of chart.

  15. Hi Sir,
    We are Developing Our Project. we are Choose canvasjs. Some specification’s are very must for use canvasjs.We want to have using canvasjs spline type chart how to put dynamic data from sql server database on normal C# and in display Mouse Cursor point will be shown in any area in the chart ist Possible to show?

    We are waiting for more the 20 more days to database connectivity for Normal C# Did not get any reference from any Site Please Help Us……

  16. Hi,
    we are trying to draw line graphs.They are working fine for Chrome and Safari But IE and Mozilla always render in lines in black color.

  17. I am trying to have mutiple bar on a chart via database to JSON

    $row[‘month’] , “y” => $row[‘2012′]);

    array_push($data_points1, $point);

    $result2 = mysqlI_query($con, “SELECT * FROM GRAPHA”);
    while($row = mysqlI_fetch_array($result2))
    $point = array(“label” => $row[‘month’] , “y” => $row[‘2013′]);

    array_push($data_points2, $point);


    echo json_encode($data_points, JSON_NUMERIC_CHECK);



    but it never shows two bars differently

    $(document).ready(function () {

    $.getJSON(“data.php”, function (result) {

    var chart = new CanvasJS.Chart(“chartContainer”, {
    title: { text: “GRAPH A” },
    data: [
    dataPoints: result
    dataPoints: result



    Pls advise.

  18. great, it is working. begin to understand how to have mutiple bar combo on one chart.

    i am using this to retrieve data from plain csv.

    $csv= file_get_contents($file);
    $array = array_map(“str_getcsv”, explode(“\n”, $csv));
    print json_encode($array);

    Noticed the output of JSON is correct. How do I have it imported / pass the info the

    $(document).ready(function () {

    $.getJSON(“data.php”, function (result) {

    var chart = new CanvasJS.Chart(“chartContainer”, {

    axisX: { suffix: ” mth”, },

    axisY: { title: “Sales”, },
    axisY2:{ suffix: ” %”, },

    title: { text: “Test” },

    data: [
    toolTipContent: “2013 : {y}”,
    dataPoints: result[0],
    toolTipContent: “2014 : {y}”,
    dataPoints: result[1],
    axisYType: “secondary”,
    toolTipContent: “2013 calc : {y}”,
    dataPoints: result[2],
    axisYType: “secondary”,
    toolTipContent: “2014 calc : {y}”,
    dataPoints: result[3],




    Is there a simpler workaround ?

  19. [[1,329,793,1121],[2,378,712,787],[3,646,883,984],[4,800,821,878],[5,797,636,927],[6,836,702,902],[7,814,588,731],[8,850,522,782],[9,934,665,523],[10,1010,683,0],[11,863,1049,0],[12,439,657,0],[null]]

    • nracer,

      You just need to parse the JSON data and convert it to the CanvasJS supported format. Below is how you can do it:

      $(document).ready(function () {
      var dataPoints = [];
      var dataPoints1 = [];
      var dataPoints2 = [];
      $.getJSON(“jsonData.json”, function (data) {
      for (var i = 0; i <= data.length – 1; i++) { for( var j = 0; j < data[i].length-1; j++){ dataPoints.push( { x: data[i][0], y: data[i][1]}); dataPoints1.push({ x: data[i][0], y: data[i][2]}); dataPoints2.push({ x: data[i][0], y: data[i][3]}); } } chart = new CanvasJS.Chart(“chartContainer”,{ axisX: { interval: 1 }, data: [ { type: “column”, dataPoints : dataPoints }, { type: “column”, dataPoints : dataPoints1 }, { type: “column”, dataPoints : dataPoints2 } ] }); chart.render(); }); });

  20. I want to set max level upto 100, The maximum line not below or more than 100 . eg I want to seen % of mark of an student. Which max level 100 and each level of 10 increase value.

    If student have 100% then one more line add in graph which i dont want (150) ..Please help me on that .

  21. I have been working with canvas js recently , its really good plugin , saves a lot of time ,
    i wanted to know if in pie chart , when i place the index labels outside , can i change the length of those
    line connectors that connects indexlabels to its equivalent area on the on the circle ?

  22. Can u help me? I want to fetch data from database through ajax and want to set ajax response into dataPoints. and i get ajax response in json format but how i can set this respone into dataPonts?

  23. How to use for loop with in data or datapoints?

    I am getting data dynamically from C# using json, how to push all values to datapoints?

    I am using mvc 4.

  24. Pingback: Еще одна библиотека построения графиков на JavaScript | ENUT

    • pavan,

      CanvasJS does not support importing or exporting data in excel format. You’ll have to do the conversion to and from CanvasJS format.

    • To be specific, In IE, animationEnabled is working for column chart and not for dougnut chart, likewise, In Firefox, animationEnabled is working for doughnut chart but not for column chart.

  25. Hello Dear, Could you please let me know how to disable bubbles on the mousehover!? and also how to disable labels!? Thanks a lot

  26. Hello Dear, Thanks a lot for your response.
    I tried these:
    valueFormatString : “”,

    but it didn’t solve it.
    I want to disable those small rectangles that appear when we do mouseover on the chart.

    Thanks for any quick response!

  27. How can we dynamically change number of datapoint under data section. i want to add or remove based on JSON data i am passing.

  28. Hi,

    I have a csv file like below in my local directory.


    Please send me the working code for the displaying the above local file into a chart.


    • Hi guys,

      I just struggled for few moments after which I was able to draw a line over a bar chart using canvasjs.

      Here is the code:

      //first I got the mean and confidence interval from a json file from php mysql

      var upper_bound=mean+confidence_interval;
      var lower_bound=mean-confidence_interval;
      var chartConTS = new CanvasJS.Chart(“chartContainer”,
      text: “Sample”
      labelFontColor: “rgb(0,75,141)”,
      axisY: {
      title: “Seconds”
      animationEnabled: true,
      exportEnabled: true,
      zoomEnabled: true,
      data: [
      type: “column”,
      color: “#2a7b86″,
      dataPoints: [
      {x: 0, label: ‘test_name’, y: mean},
      type: “line”,
      dataPoints: [
      { x: 0, y: upper_bound },
      { x: 0, y: lower_bound},

  29. Hi,

    I have return on line with live update for every 10 sec and it is working fine. But the problem is when I have open the chart application as background tab and when I try to open that tab the browser getting hanged. Is their any solution for this.


  30. Hi,

    I have a question about “Multi Series Column Chart”. I don’t want to show the datapoint names in labels on axisX, instead I would like to show there a month and a year. How can I do that?

  31. dataPointMaxWidth property is not working in the alternate way of setting:

    chart.options.dataPointMaxWidth = 40;

    Or am I doing it wrong?

    • You can instantiate a new Chart object by sending the ID of div element where the chart is to be rendered. You can also pass DOM element instead of ID.
      Here is the jsFiddle to render charts based on class name.

  32. Hi,
    I am using the column chart, but when there is more than 10 bars in the chart it does not show all the label. it shows all the bars but half of them with no labels. how can i force it to show all the labels.

  33. i need multi series line chart ,i want to take datapoints from two different text files, and assign one file values for one line and another for second line, is it possible with canvas js?

    • Absolutely, it is possible with CanvasJS!!
      First you take the values into two datapoints from the two files using Ajax, then you can pass the datapoints as elements in the data array for the chart. Simple.

  34. Hi guys! I have a problem “converting” json object to dataPoints. Here is my function

    $scope.getDataPoints = function () {
    angular.forEach($scope.risultati, function (ris) {
    $scope.dataPoints += “{ label: \”” + ris.IDCommessa + “\”, y: ” + ris.Valore + ” },”;
    $scope.dataPoints += “]”;

    but i get this error:

    HTML1300: È stata eseguita la navigazione.
    TypeError: Impossibile recuperare la proprietà ‘getTime’ di un riferimento nullo o non definito
    at Chart.prototype._processMultiseriesPlotUnit (http://localhost:53937/Scripts/canvasjs.js:2817:5)
    at Chart.prototype._processData (http://localhost:53937/Scripts/canvasjs.js:2769:6)
    at Chart.prototype.render (http://localhost:53937/Scripts/canvasjs.js:2396:3)
    at render (http://localhost:53937/Scripts/canvasjs.js:14385:5)
    at $scope.toChart (http://localhost:53937/App/controllers/risultatiController.js:72:9)
    at Anonymous function (http://localhost:53937/App/controllers/risultatiController.js:109:13)
    at Anonymous function (http://localhost:53937/Scripts/angular.js:10250:13)
    at processQueue (http://localhost:53937/Scripts/angular.js:14745:11)
    at Anonymous function (http://localhost:53937/Scripts/angular.js:14761:27)
    at Scope.prototype.$eval (http://localhost:53937/Scripts/angular.js:15989:9)

    it says “Impossible to get the property getTime of a null or not defined object”

    Could you help me please?

  35. i need to get pie chart which having like 20% of dotted portion 40% lines and 40% grids is it possible with canvs js if so how to make it?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>