Retrieve an array of the points currently displayed on the Chart.js graph

While utilizing Chart.js with zoom and pan capabilities, I am attempting to create a function that exports only the content visible on the canvas to a CSV file.

However, I am struggling to identify how to retrieve solely the visible data points after user interaction with zooming and panning.

Although I am aware that inspecting myChart.data.datasets would provide all the data points in the chart, it does not cater to retrieving just the currently visible ones.

var config = {
    type: 'line',
    data: {
        // data received from an API call
    },
    pan: {
        enabled: true,
        mode: 'xy'
    },
    zoom: {
        enabled: true,
        mode: 'xy'
    },
    bezierCurve : false
};
};

var ctx = document.getElementById('myChart').getContext('2d');
window.myChart = new Chart(ctx, config);

$('#exportTheseRunsToCSV').on('click', function() {
    // something like myChart.getVisibleDataPoints() ???
    console.log(chart)
    console.log(chart.data.datasets)
});

There should be an internal method for accessing the visible points since I already have a function to export the current visible points as a PNG image, which accurately captures what is currently displayed on the canvas:

<a id="exportTheseRuns" class="text-white" href="#" download="image.png" download><i class="fas fa-download"></i> Export to PNG</a>

$('#exportTheseRuns').on('click', function() {
    $('#exportTheseRuns').attr('href', myChart.toBase64Image());
})

The .toBase64Image() function appears to internally achieve what I require, capturing only the visible points. Yet, it returns a Base64 URI which cannot directly be used with my arrayToCSV function.

Answer №1

The chart object has two properties, minIndex and maxIndex, which allow you to use the slice method on the dataset to extract only the visible values.

Below is a code snippet demonstrating how to utilize the functions onPanComplete and onZoomComplete provided by a plugin to display the visible values after panning or zooming in on the chart:

function getVisibleValues({
  chart
}) {
  let x = chart.scales["x-axis-0"];

  document.getElementById("vv").innerText = JSON.stringify(chart.data.datasets[0].data.slice(x.minIndex, x.maxIndex + 1));
}

new Chart(document.getElementById("chart"), {
  type: "line",
  data: {
    labels: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'],
    datasets: [{
      data: [0, 1, 2, 4, 8, 16, 32, 64, 128, 256]
    }]
  },
  options: {
    maintainAspectRatio: false,
    scales: {
      xAxes: [{
        ticks: {
          min: 'c',
          max: 'h'
        }
      }]
    },
    plugins: {
      zoom: {
        pan: {
          enabled: true,
          mode: 'x',
          onPanComplete: getVisibleValues
        },
        zoom: {
          enabled: true,
          mode: 'x',
          onZoomComplete: getVisibleValues
        }
      }
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6102090013154f0b1221534f584f50">[email protected]</a>"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="254d44484840574f5665170b150b1d">[email protected]</a>"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d0e050c1f19071e401d01180a040340170202002d5d435a4359">[email protected]</a>"></script>
<canvas id="chart" style="max-height:125px"></canvas>
<p>
  Visible values: <span id="vv"></span>
</p>

Answer №2

The function toBase64Image does not do exactly what you are looking for; it simply retrieves the data URL from the canvas element.

Visit toBase64Image on github.com/chartjs

toBase64Image: function() {
  return this.canvas.toDataURL.apply(this.canvas, arguments);
},

You can access updated chart data using onZoomComplete and onPanComplete; both functions provide an object with a property named chart which contains additional information about the current zoom level. However, it seems that some calculations or work may be required to determine the visible points...

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

Generating a list of objects from MongoDB using Node.js

Hello everyone, I am currently learning about mongodb and node js for the first time, so please bear with me if my question is too basic. I am working with a schema that looks like this: var mongoose = require('mongoose'); var CatSchema = new m ...

Toggle the status of active to inactive instantaneously with the click of a

Incorporating DataTables with ajax using PHP CodeIgniter Framework has presented me with a challenge. I am struggling to toggle between Active and Inactive buttons seamlessly. My desired outcome: When the Active button is clicked, it should transition ...

Challenges with managing VueJS methods and understanding the component lifecycle

I'm facing an issue with my code. The function retrieveTutorials() is not transferring the information to baseDeDatosVias as expected. I've attempted to change the function to a different lifecycle, but it hasn't resolved the problem. The so ...

The sub-menu is being obscured by a PDF element in Internet Explorer, causing visibility issues

I have an object type tag on my page that displays a PDF file. Everything is functioning correctly, but in Internet Explorer, my sub-menu is being hidden behind the object tag. var objTag = $('<object></object>') .attr({ data: source ...

Using ASP.NET to retrieve data with AJAX and pass parameters to a web method

Looking for assistance with a web method I have created: [WebMethod] [ScriptMethod(UseHttpGet = true)] public static string test(string Name, int? Age) { return "returned value"; } Below is the ajax call I am attempting: $.ajax({ type: "GET", ur ...

The building process of Ember encountered an error due to a problem with the broccoli builder

I'm currently working on an Ember project and facing an issue while trying to upgrade the version from 2.8 to 3.5.0. After changing the version and some dependencies, I encountered the following error : Error stack Even after attempting to resolve i ...

Inefficiency of the Array.map function in Scala

I'm curious as to why the implementation of the Array.map(f: A=> B) method is over 5 times slower compared to the following code: val list = Array(1, 2, 3, 4, 5, 6, 7, 8, 9) val newList = new Array[Int](size) var j = 0 while (j < size) { n ...

Combining values from multiple flat arrays into one nested array

As a beginner in PHP, I find myself feeling overwhelmed. I'm working on a file listing script that scans a directory and generates a list of file paths like this: 2014/1Q/ES/PDFs/141QES_01.pdf My goal is to loop through this list (which is quite lo ...

Manipulating Arrays in JavaScript: Techniques for Extracting Values Buried in Nested Objects

I am working with an array of objects that contain multiple "Book" objects with dynamic keys. My goal is to filter the objects in the array to only include those that have at least one new "Book" object. For example: const arr = [ { id: '123&ap ...

Attempting to utilize solution for the "ajax-tutorial-for-post-and-get" tutorial

I've been exploring the implementation of the second answer provided in a post about Ajax tutorials on a popular coding forum. Despite following the instructions, I encountered an issue where the $.ajax script, triggered by an "onclick" function, only ...

Submitting data via AJAX using the method parameter

I have a specific ajax form that requires serialization and the manual setting of the _method for the data form. This is how I am currently handling it. $.ajax({ url: http://someposturl.com/object, type: 'POST', ...

Using a for loop in Flot to display data from a JSON file

I am working on creating a dynamic flot graph that will adjust based on the data provided. The information for my flot graph is in JSON format, and here's an example of the dataset: { "total":[[1377691200,115130],[1377694800,137759],[1377698400,1 ...

Utilizing nested grouping in mongoose schemas

I am facing a challenge while attempting to execute a nested group query in MongoDB. Is there a way to group data by both date and campaign ID, ensuring that each campaign ID contains a nested array of creatives with their respective data (views and clicks ...

Calculating response time in Selenium with VB.NET: A comprehensive guide

I'm working on creating an automated test to calculate the average response time for a screen's responsiveness. My tools of choice are Selenium and VB.net. Can someone please provide guidance on how to accurately calculate this? The waitforpage() ...

Send Components to another component without specific TypeScript typespecified

Struggling with a situation where I am faced with the challenge of working around strongly typed variables. The issue arises with a set of icons as components and an icon wrapper component. The wrapper component requires a themeMode variable to determine ...

Contrast and remove the elements within jQuery array objects

As part of my data collection process, I am creating arrays to store lists of users for each request. Here is the code snippet that shows how I populate these arrays: $.each(data, function (i, item) { jQuery.each(array, function (index, data) { ...

Encountering an Uncaught TypeError while trying to read properties of undefined (specifically 'remove') during a Change event is causing an issue for me

Looking to update the icons by changing the class from .fa-plus to .fa-minus for this specific menu section <div class="accordion-menu"> <h2 class="accordion-header" id="subseccOne"> ...

Update the PHP webpage dynamically by utilizing AJAX and displaying the PHP variable

I am working on a PHP page that includes multiple queries, and I would like to be able to include this page in my index.php file and display the results with an automatic refresh similar to the Stack Overflow inbox feature. Is there a way to achieve this ...

Harnessing the power of external Javascript functions within an Angular 2 template

Within the component, I have a template containing 4 div tags. The goal is to use a JavaScript function named changeValue() to update the content of the first div from 1 to Yes!. Since I am new to TypeScript and Angular 2, I am unsure how to establish comm ...

Is it advisable to utilize $locationProvider in AngularJS version 1.3.14?

Attempting to utilize html5Mode to remove # from the url in SPAs resulted in an error when using $locationProvider in AngularJS v 1.3.14. The reason for this error is unclear. The code snippet and console error are provided below for reference. Front End: ...