Create two chart with same Javascript function - Javascript Chart.js

Javascript examples for Chart.js:Chart Configuration

Description

Create two chart with same Javascript function

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script> 
      <style id="compiled-css" type="text/css">
.panel {//w ww. j  a  va 2s  .  co m
   padding-left: 5px;
   background: #fff;
   box-shadow: 0 0 5px 0 #999;
   border-radius: 5px;
   margin: 0 auto;
   width: 100%;
   height: 300px;
   margin-top: 2em;
   max-width: 600px;
}
      </style> 
      <script type="text/javascript">
    window.onload=function(){
const DATEFORMAT = 'hour';
const DATEFORMATS = {
  'hour': 'hh:mma',
  'day': 'MMM DD',
  'week': 'MMM DD',
  'month': 'MMM'
};
drawChart('canvas1', 10, true);
drawChart('canvas2', 30, false);
function drawChart(canvasId, totalValues, hideLastXLabel) {
  new Chart(document.querySelector('#'+canvasId), {
      type: 'line',
      data: getData(totalValues),
      options: {
          layout: {
            padding: {
              right: 10
            }
          },
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero:true
              }
            }],
            xAxes: [{
              gridLines : {
                display : false
              },
              ticks : {
                callback: (value,index,values) => {
                  if (hideLastXLabel && index+1 >= values.length) {
                    return '';
                  }
                  return DATEFORMATS[DATEFORMAT]? moment(value).format(DATEFORMATS[DATEFORMAT]) : value.toString();
                }
              }
            }]
          }
      }
  });
}
function getData(total) {
  var data = {
    labels: [],
    datasets: [{
      data: [],
      label: 'Data',
      lineTension: 0,
      backgroundColor:"rgba(128, 203, 196,0.45)",
      borderColor:"#80cbc4",
      pointBackgroundColor: "#80cbc4",
      pointBorderWidth: 2,
      hoverBorderColor:"#80cbc4",
      pointBorderColor:"#fff",
      pointRadius: 5,
      pointHoverRadius:5
    }],
  }
  var end = Date.now();
  var start = total < 2? end : end-((total-1)*1000*60*60);
  for (var i=0; i<total; i++) {
     data.labels.push(start+(i*1000*60*60));
     data.datasets[0].data.push(Math.round(20*Math.random()));
  }
  return data;
}
    }

      </script> 
   </head> 
   <body> 
      <div class="panel">
         <canvas id="canvas1"></canvas>
      </div> 
      <div class="panel">
         <canvas id="canvas2"></canvas>
      </div>  
   </body>
</html>

Related Tutorials