viernes, 25 de noviembre de 2016

Canvas Html5 JAvascript Creating Dynamic Charts Graficos con JAvascript

http://canvasjs.com/docs/charts/how-to/creating-dynamic-charts/

Creating Dynamic Charts

CanvasJS allows you to create dynamic charts that update at a given interval. Dynamic charts are required when you are displaying data that changes with time like stock price, temperature, etc. Technically, dynamic charts are created the same way as any other chart type except that dataPoints are added/removed at a predefined interval.
All available charts in CanvasJS support dynamic updates including Line Chart, Area Chart, Column Chart etc.
Here are the steps for creating Dynamic Chart.

Step1:

Create a basic chart as usual. But, assign dataPoints to a pre-defined variable (dps in this example)
  1. var dps = [{x: 1, y: 10}, {x: 2, y: 10}, {x: 3, y: 10}, {x: 4, y: 10}, {x: 5, y: 10}]; //dataPoints.
  2.  
  3. var chart = new CanvasJS.Chart("chartContainer",{
  4. title :{
  5. text: "Live Data"
  6. },
  7. axisX: {
  8. title: "Axis X Title"
  9. },
  10. axisY: {
  11. title: "Units"
  12. },
  13. data: [{
  14. type: "line",
  15. dataPoints : dps
  16. }]
  17. });
  18.  
  19. chart.render();

Step2:

Now, we see that values inside dps are being rendered. Now, in order to make the chart dynamic, we just need to change dps array as required and then call chart.render() again.
  1. var xVal = dps.length + 1;
  2. var yVal = 100;
  3. var updateInterval = 1000;
  4.  
  5. var updateChart = function () {
  6. yVal = yVal + Math.round(5 + Math.random() *(-5-5));
  7. dps.push({x: xVal,y: yVal,});
  8. xVal++;
  9. chart.render();
  10.  
  11. // update chart after specified time.
  12.  
  13. };
  14. setInterval(function(){updateChart()}, updateInterval);
In the above code, we are calling updateChart method every second. Each time updateChart adds a new dataPoint and calls chart.render().

Step3:

If you don’t want the dataPoints to keep getting accumulated, you can remove old values from the beginning of the Array as shown below.
  1. if (dps.length > 10 )
  2. {
  3. dps.shift();
  4. }

Finalising

To summarize, in order to create live charts, you should update the array containing the dataPoints and call chart.render()
Below is the compilation of final code.

1 comentario: