Extract data for the chart from the Canvas element using Chart.js

There are multiple Chart.js charts that may need to be updated at a later time.

Is it feasible to retrieve the myChart object from the canvas element when needing to update the chart, or is it necessary to preserve each myChart object in the global scope?

for(var i=1; i<=5; i++) {
  createChart(i);
}

function createChart(i) {
  var $chart = $('<canvas id="chart-' + i + '" width="400" height="400"></canvas>').appendTo('body');
  var myChart = new Chart($chart, {
    data: {
      datasets: [{
          data: [Math.random(), Math.random(), Math.random(), Math.random()]
      }]
    }
  });
}

Below is some pseudo-code on how I would like to update, for example, chart 2 at a later time:

var updateChart = $('#chart-2'); // This is where I'd need to extract the chart data from the canvas element

updateChart.data.datasets[0].data = updateChart.data.datasets[0].data.push(Math.random());

updateChart.update();

Answer №1

One useful feature provided by the ChartJS API is the getChart method, which allows you to achieve your desired outcome:

You can use Chart.getChart('chart-2') to select a chart by canvas ID
// OR
You can also select using the canvas element like this:
let canvas = document.querySelector('#chart-2')
let chart = Chart.getChart(canvas);

// Once selected, you can update your chart with new data and labels
chart.data.datasets[0].data = newData;
chart.data.labels = newLabels;
chart.update();

Answer №2

Iterate through each chart instance using Chart.helpers.each() and log each instance to the console.

For more information, refer to: https://example.com/chart-instances

Answer №3

It is advisable to organize and store all data intended for the chart into arrays. After updating the array, you can then transmit:

via HTTP/AJAX/SOCKET.IO

a notification to the client and refresh the chart accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having issues with implementing PrimeNG components (Directive annotation not detected)

Having difficulty integrating PrimeNG components (beta5) with Angular2 (rc.1). Whenever attempting to utilize a component, such as the menubar, the following error is consistently encountered: No Directive annotation found on Menubar New to Angular and ...

Scrolling infinitely within the side menu using ion-infinite-scroll

I'm encountering an issue with using Ion-infinite-scroll within ion-side-menu, as the load more function is not being triggered. Is it permitted to utilize ion-infinite-scroll inside ion-side-menu? Although I have added the directive, the method "lo ...

Ways to decrease and transform a collection of objects?

What is the best way to condense and transform this object array into a new array? Here is the data I am working with: var objArray = [{ state: 'NY', type: 'A', population: 100 }, { state: 'NY', ty ...

Deleting Firestore ancestor documents and sub-collections that do not exist

My goal is to tidy up my collection data. The collection I'm working with is named "teams". Within this collection, there is a sub-collection called "players". I used a basic delete query in Firestore to remove the document under ...

Angular JS - Selecting Directives on the Fly

I'm currently developing an application where users can choose from various widgets using a graphical user interface (GUI). My plan is to integrate these widgets as angular directives. THE CONTROLLER $scope.widgets = ['one', 'two' ...

Discover the secret to unlocking hidden buttons and triggering their functions with a simple click

I am currently working on improving the usability of a webpage. There is a drop-down menu with a 'Delete' button that I would like to streamline. Upon inspection, here is the code snippet: <a title="" class="ajax-command" command="deletePost" ...

Utilize jQuery to wrap text within <b> tags and separate them with <br> tags

Upon receiving output in html string format from services, I am presented with the following: "<html>↵<h1>↵Example : ↵<br>Explanation↵</h1>↵<hr>↵<b>key1 : ABCD <br>key2 : 2016-10-18-18-38-29<br> ...

Is it possible to display a upload progress indicator without using a specialized ajax uploader

I'm working on a Rails application that uploads large files (~300mb). Is there a way to incorporate a progress indicator without relying on a specific HTML5 uploader or installing the nginx server module? Can this be achieved simply with the standard ...

Stacking divs by rotating them on top of each other

It seems like I'm facing a quick fix issue that's really messing with my mind. Here's the situation: I have a custom dashboard with multiple divs containing rotating data. However, when the page refreshes for the first time, all the data loa ...

What is the best way to navigate to a component that has been imported in Vue.js?

I have knowledge of Vue's scrollBehavior function, but I am struggling to integrate it with my existing code. On my Index page, I have sections composed of imported Vue components like this: <template> <div class="Container"> <Ab ...

What is causing the child table (toggle-table) to duplicate every time a row in the parent table is clicked?

After creating a table containing GDP data for country states, I've noticed that when a user clicks on a state row, the child table displaying district GDP appears. However, there seems to be an issue with the child table as it keeps repeating. I&apos ...

Difficulty in accurately retrieving the value in a PHP echo statement using jQuery

$id = "123"; When on the page book.php, $id is passed to an external jquery-book.php file. <script type="text/javascript"> var id = '<?php echo $id; ?>'; </script> <script type="text/javascript" src="jquery-book.php"& ...

Is there a way to repurpose a displayed.bs.collapse function for multiple uses?

I have implemented a JavaScript snippet that enables a collapse feature with color and chevron changes based on its open or closed state. Now, I am attempting to replicate this functionality for a different button but haven't had success by changing t ...

What is the process for updating the h1 header with text entered into an input field?

I'm working on an assignment that requires me to change the h1 heading to reflect whatever is entered into the input field. To accomplish this, I need to create a function using getElementByID. Here's what I've done so far: <!DOCTYPE htm ...

Errors in Javascript unit testing: despite being stubbed, functions are still being activated

I have encountered issues while writing unit tests, and I am currently facing errors that I am trying to troubleshoot. The specific unit test concerns the index.ts file, which calls the features/index.ts file. To simulate the default export from features/ ...

The property '_renderItem' cannot be defined as undefined

Seeking assistance with my code... Could someone please help? $(document).ready(function() { //$('#search input[name="filter_name"]').attr("x-webkit-speech", "x-webkit-speech") $('#search input[name="input-search-menu"]').autocompl ...

Limit the rotation of jQuery and CSS3 elements to always turn in a clockwise direction

Utilizing the jQuery transit plugin, I am rotating a block element with 4 navigation controls. Each time a nav item is clicked, the block rotates to the specified custom data attribute of that nav item - either 0, 90, 180, or 270 degrees. While I have suc ...

Tips for transforming a date string into a Date object

What is the best way to transform a date string into a Date object? A sample date string for reference: 12.31.2009 11:12:00 ...

Using JavaScript/jQuery to analyze POST values just before submission

Currently facing a dilemma as my company is in the process of redesigning its website. I find myself stuck trying to come up with a temporary fix for an issue on the existing site. The solution requires the use of JavaScript or jQuery. The problem arises ...

changing the name of a variable within ng-include

Here is some important HTML code: <ng-include src="'app/views/order.html'"></ng-include> Within the scope of this ng-include, there is a variable called trade. The structure of the trade variable is as follows: var trade = { or ...