CanvasJS - Documentation

Getting Started

Installation

CanvasJS can be integrated into your project in several ways:

1. CDN: The easiest way to get started is by including the CanvasJS script directly from a CDN. Add the following line within the <head> section of your HTML file:

<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

Replace "https://canvasjs.com/assets/script/canvasjs.min.js" with the appropriate CDN link if you are using a different version or a mirror.

2. Download: Download the CanvasJS library from the official website and include it in your project. Extract the downloaded archive and include the canvasjs.min.js file in your HTML using a <script> tag, similar to the CDN method. Place the file within your project’s accessible JavaScript directory.

3. npm (Node Package Manager): If you’re using npm, install CanvasJS using the following command:

npm install canvasjs

Then, import it into your JavaScript file:

import CanvasJS from 'canvasjs';
// or
import * as CanvasJS from 'canvasjs';

Remember to adjust your build process accordingly to include CanvasJS in your final output.

Creating Your First Chart

Once CanvasJS is installed, creating a simple chart is straightforward. The following code creates a basic column chart:

<!DOCTYPE HTML>
<HTML>
<HEAD>
<title>CanvasJS Example</title>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</HEAD>
<BODY>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
<script>
window.onload = function () {
  var chart = new CanvasJS.Chart("chartContainer", {
    animationEnabled: true,
    title:{
      text: "Simple Column Chart"
    },
    data: [{
      type: "column",
      dataPoints: [
        { label: "Apple",  y: 10  },
        { label: "Orange", y: 15  },
        { label: "Banana", y: 25  }
      ]
    }]
  });
  chart.render();
}
</script>
</BODY>
</HTML>

This code creates a div element with the id “chartContainer” to hold the chart and then uses JavaScript to create a CanvasJS chart object. Replace "https://canvasjs.com/assets/script/canvasjs.min.js" with your local path if you downloaded the library. The dataPoints array specifies the data for the chart.

Basic Chart Configuration

The CanvasJS chart object is highly configurable. The basic structure involves:

You can customize various aspects of your chart using these properties and other options detailed in the full CanvasJS documentation. Refer to the documentation for a complete list of available options and their functionalities. Remember to consult the API documentation for advanced configurations and chart types.

Chart Types

Column Chart

Column charts are ideal for comparing different categories or groups of data. Data points are represented as vertical columns, making it easy to visually compare magnitudes. CanvasJS provides extensive customization options for column charts, including:

Bar Chart

Bar charts function similarly to column charts, but with horizontal bars instead of vertical columns. This orientation can be more effective when dealing with many categories or long labels. Customization options mirror those of column charts, including stacking and 100% stacking.

Line Chart

Line charts are best suited for visualizing trends and patterns over time or across continuous data. Points are connected with lines to show the progression of values. Features include:

Area Chart

Area charts are an extension of line charts, filling the area under the line. This visual representation emphasizes the magnitude of data values over time or across categories. They offer similar customization to line charts, with the added option of stacked and 100% stacked area charts.

Pie Chart

Pie charts are excellent for showcasing proportions or percentages of a whole. Each slice represents a data point’s contribution to the total. Options include:

Scatter Chart

Scatter charts display data points as individual markers in a two-dimensional space, showing the relationship between two variables. They are useful for identifying correlations or clusters in data. Features include:

Bubble Chart

Bubble charts extend scatter charts by adding a third dimension: the size of each bubble corresponds to the value of a third variable. This helps in visualizing relationships between three variables simultaneously.

Doughnut Chart

Doughnut charts are similar to pie charts, but with a hole in the center. This central hole can be used to display additional information or branding. Customization options are largely the same as pie charts.

Funnel Chart

Funnel charts visually represent a process or sequence of events, showing how a quantity changes at each stage. The width of each stage is proportional to the value at that stage.

Pyramid Chart

Pyramid charts are similar to funnel charts but are used to represent hierarchical data where the levels may not necessarily follow a decreasing trend as in funnel charts.

Step Line Chart

Step line charts are a variation of line charts where data points are connected by horizontal and vertical lines, creating a stepped appearance. This style is particularly useful for visualizing discrete data or step-wise changes.

Spline Chart

Spline charts use smooth curves to connect data points, creating a visually appealing representation of trends, particularly useful when data points are somewhat noisy or irregular.

Range Column Chart

Range column charts display a range of values for each category using columns, with the height of the column representing the range’s extent.

Range Bar Chart

Range bar charts are the horizontal equivalent of range column charts.

Range Area Chart

Range area charts display the range of values as shaded area between two lines, highlighting the variation or uncertainty within data.

Candlestick Chart

Candlestick charts are primarily used to visualize financial data, showing the open, high, low, and close prices for a given period.

Box and Whisker Chart

Box and whisker charts (box plots) summarize data by displaying quartiles and outliers. They are useful for comparing the distribution of data across different categories.

Map Chart

Map charts display data geographically on a map. CanvasJS provides support for various map projections and data sources.

Waterfall Chart

Waterfall charts visualize the cumulative effect of positive and negative values, showing how an initial value changes over a series of steps. This is useful for displaying financial statements or resource allocation.

Chart Features

Axes

CanvasJS charts utilize axes to represent data values along the horizontal (x-axis) and vertical (y-axis) dimensions. Axes are highly customizable:

Titles and Subtitles

Charts can include titles and subtitles to provide context and description. These can be styled using various properties, including font size, color, and weight.

Legends

Legends provide a visual key to identify different series or data points within a chart. They can be positioned and styled according to your preference.

Data Labels

Data labels display the values of individual data points directly on the chart. This can improve data readability, particularly for charts with many data points or complex visualizations. Position and formatting of data labels are highly configurable.

Tooltips

Tooltips provide detailed information about a specific data point when the user hovers over it. Tooltips typically display the data point’s label and value, and can be customized to show additional information.

Animations

CanvasJS supports various chart animations, enhancing the user experience and making data visualization more engaging. Animations can be enabled or disabled globally or on a per-series basis. The animation speed and type can also be customized.

Data Points

Data points represent the individual data values in a chart. They can be customized in numerous ways, including:

Events

CanvasJS allows you to handle various events, such as clicking on a data point or the chart area. This enables you to add interactive elements to your charts, such as drill-down functionality or custom tooltips.

Zoom and Pan

Interactive zooming and panning allow users to explore large datasets or detailed sections of a chart. This feature enhances the usability of charts with a high volume of data.

Exporting Charts

CanvasJS provides options for exporting charts in various formats (e.g., PNG, JPEG, SVG, PDF). This allows users to save or share charts easily.

Themes

Predefined themes provide consistent styling across your charts. CanvasJS offers several built-in themes, and you can also create custom themes to match your application’s branding.

Responsive Design

CanvasJS charts are responsive, adapting to different screen sizes and devices. Charts automatically adjust their layout and dimensions to fit the available space, ensuring optimal viewing on various screens.

Data Handling

Data Binding

CanvasJS offers flexible data binding capabilities. You can directly bind your data to the chart using JavaScript arrays or objects. The dataPoints array within each data series is the primary method for binding data. Data points are typically objects with at least a y property (representing the data value) and optionally a label property (representing the category label). For example:

var dataPoints = [
  { y: 10, label: "Category A" },
  { y: 15, label: "Category B" },
  { y: 20, label: "Category C" }
];

More complex data structures can be used depending on the chart type and desired visualization.

Data Sources

CanvasJS supports various data sources. While you can directly bind data using JavaScript arrays (as shown above), you can also fetch data from external sources such as:

Data Updating

CanvasJS allows you to dynamically update chart data after the initial rendering. This is useful for creating real-time charts or visualizing data that changes over time. To update data, you modify the dataPoints array of your data series and then call the render() method of the chart object again. For example:

// ... existing code ...

chart.data[0].dataPoints.push({ y: 25, label: "Category D" }); // Add a new data point
chart.render(); // Rerender the chart

CanvasJS handles the efficient update of the chart’s visualization based on the modified data.

Data Formatting

CanvasJS provides options for formatting data displayed in the chart and its components (labels, tooltips, etc.):

Large Datasets

Handling large datasets efficiently is crucial for performance. CanvasJS employs various optimization techniques to render charts with a large number of data points smoothly. Consider these strategies for optimal performance with large datasets:

Remember to profile your application’s performance to identify bottlenecks and tailor your approach accordingly. Using appropriate data handling techniques ensures that your CanvasJS charts remain responsive and efficient even with extensive datasets.

Customization

Styling Charts

CanvasJS offers extensive styling options to customize the appearance of your charts. You can modify various aspects, including:

Customizing Tooltips

Tooltips provide interactive information about data points. You can customize tooltips to display more than just the default values:

Adding Custom Elements

CanvasJS allows you to extend its capabilities by adding custom elements to your charts. This can be achieved by directly manipulating the chart’s underlying SVG or canvas elements, or by utilizing CanvasJS’s event handling to add elements dynamically:

Using Plugins

CanvasJS plugins provide additional functionalities that extend the core library. While CanvasJS doesn’t have an official plugin system in the same manner as some other libraries, community-created extensions or custom additions to your project could be considered plugins. These custom additions should be well-documented and provide a clear way to integrate with existing CanvasJS charts. If you create a reusable extension, consider sharing it with the community!

Remember to always refer to the official CanvasJS documentation for the most up-to-date information and best practices on customization.

Advanced Topics

Chart Interactions

Beyond basic hover tooltips, CanvasJS supports a range of interactive features that enhance user engagement and data exploration:

Performance Optimization

For large or complex charts, optimizing performance is critical to maintain a responsive user experience. Key strategies include:

Server-Side Integration

Integrating CanvasJS with server-side technologies allows you to create dynamic charts with data fetched from databases or APIs:

Accessibility

Creating accessible charts ensures that users with disabilities can interact with and understand the data presented. Key aspects of accessibility include:

Remember that accessibility is a continuous process; regular testing with assistive technology is recommended.

API Reference

This section provides a concise overview of the key CanvasJS API objects. For complete details, including all properties and methods, refer to the comprehensive CanvasJS API documentation available on the official website.

Chart Object

The Chart object is the central element of the CanvasJS API. It represents the entire chart and provides methods for creating, updating, and manipulating the chart’s appearance and behavior. Key properties and methods include:

Axis Object

The Axis object represents a single axis (x-axis, y-axis, etc.) within a chart. Properties control its appearance and scaling. Key aspects include:

The Axis object has variations depending on the chart type and the axis (e.g., axisX, axisY, axisY2).

Data Series Object

The DataSeries object represents a single data series within a chart. It defines the type of data series (e.g., column, line, pie) and its data points. Important properties include:

Data Point Object

The DataPoint object represents a single data point within a data series. It contains the data value and other associated information. Key properties include:

Tooltip Object

The Tooltip object controls the appearance and behavior of tooltips displayed when hovering over data points. Key properties:

Legend Object

The Legend object controls the chart legend’s appearance and position. Key properties:

Utilities

CanvasJS provides utility functions for various tasks. These are typically not directly properties of chart objects, but are available within the CanvasJS namespace. Examples include functions for:

Consult the CanvasJS API documentation for a complete list of utilities and their functionalities. Remember that the specific methods and properties might vary slightly depending on the CanvasJS version. Always check the latest documentation for the most accurate information.

Troubleshooting

Common Errors

This section outlines some common errors encountered when working with CanvasJS and provides potential solutions.

Debugging Tips

Effective debugging is essential for resolving CanvasJS issues:

Community Support

If you’ve exhausted the above troubleshooting steps and still need assistance, consider reaching out to the CanvasJS community:

Remember to always provide context such as your CanvasJS version, browser, and relevant code snippets when seeking help from the community. Clear and concise descriptions of the problem significantly improve your chances of receiving a timely and effective solution.