search
HomeWeb Front-endJS TutorialAn Introduction to Chart.js 2.0

An Introduction to Chart.js 2.0

This article is part of our Modern JavaScript anthology. For a comprehensive guide to modern JavaScript, explore SitePoint Premium and download your copy.

Peer reviewed by Tim Severien and Simon Codrington. Thanks to all SitePoint's peer reviewers!

Data-heavy websites demand effective data visualization. Raw numbers are hard for humans to grasp; charts and graphs offer intuitive, accessible alternatives, even for non-English speakers. Clear visuals enhance understanding and website appeal.

This tutorial introduces Chart.js, a JavaScript charting library. Through six examples, we'll demonstrate its use and configuration.

Key Features of Chart.js 2.0:

  • Versatile and user-friendly JavaScript library for diverse chart creation.
  • Simple installation and quick learning curve.
  • Supports various chart types: line, bar, radar, polar area, pie, and doughnut. Chart type is easily changed via the type property.
  • Enhanced features: mobile responsiveness and integrated titles.
  • Customizable interactivity (e.g., toggling datasets via legend clicks).
  • Extensive customization options for appearance (colors, tooltips, animations).

Why Chart.js?

Chart.js balances ease of use with powerful customization. It avoids the steep learning curve of more complex libraries while offering ample flexibility. Its eight chart types cover most visualization needs. The active open-source community ensures high-quality maintenance. Version 2.0 introduced significant syntax improvements and mobile support. This tutorial uses Chart.js 2.0. A section on the 1.0 to 2.0 transition is included.

Installing Chart.js:

Chart.js prioritizes simplicity. The easiest installation method is via a CDN:

<🎜>

You'll also need a <canvas></canvas> element:

<canvas id="myChart"></canvas>

Alternatively, use a package manager (see the Getting Started guide for details).

Let's explore Chart.js's capabilities.

Line Chart:

This minimal line chart demonstrates Chart.js's core structure:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
    datasets: [{
      label: 'apples',
      data: [12, 19, 3, 17, 6, 3, 7],
      backgroundColor: "rgba(153,255,51,0.4)"
    }, {
      label: 'oranges',
      data: [2, 29, 5, 5, 2, 3, 10],
      backgroundColor: "rgba(255,153,0,0.4)"
    }]
  }
});

See CodePen Example

Explanation:

  • ctx: Gets the 2D rendering context of the <canvas></canvas>.
  • new Chart(ctx, { ... }): Creates the chart object. type specifies the chart type; data holds the chart data. Array indices determine graph positions.

Pro Tip: Clicking legends toggles datasets. This applies to all chart types.

Bar Chart:

Simply change type: 'line' to type: 'bar' in the previous example.

See CodePen Example

Radar Chart:

Change type to 'radar'. Adjust backgroundColor and borderColor for better readability with overlapping data.

See CodePen Example

Polar Chart:

Change type to 'polarArea'. Polar charts visualize single datasets.

See CodePen Example

Pie and Doughnut Charts:

Change type to 'pie' or 'doughnut'. Doughnut charts use cutoutPercentage to control the hole size.

See CodePen Example (Pie) See CodePen Example (Doughnut)

Chart.js Configuration (options):

The options property allows extensive customization:

  • Titles: Add titles using options: { title: { display: true, text: 'My Chart' } }.
  • cutoutPercentage: Controls the doughnut chart's hole size (0-50).
  • Stacked Bar Charts: Use options: { scales: { yAxes: [{ stacked: true }] } } for stacked bars.

Event Handling:

Customize legend click behavior:

<🎜>

Example: Dynamic Caption Update:

See CodePen Example This example updates a caption based on legend clicks.

Chart.js 2.0 vs. 1.0:

Key differences:

  • Chart declaration: 2.0 uses a single new Chart() call with type, data, and options. 1.0 uses function chaining.
  • Mobile support: 2.0 includes native mobile support.
  • Integrated titles: 2.0 offers built-in titles.

Conclusion:

Chart.js is ideal for rapid chart prototyping. Its diverse chart types and ease of use make it a valuable tool for any web developer. Refer to the official Chart.js documentation for comprehensive details.

(Note: Replace https://www.php.cn/link/144b646e159cb47f13a4ebb4c8d00628 with actual CodePen links for each chart type.)

The above is the detailed content of An Introduction to Chart.js 2.0. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)