[Chartjs]-How do I set a default chart type and a default scale type in Chart.js?

2๐Ÿ‘

โœ…

If you want to avoid repetitive configuration, you may want to declare and initialize constants or variables with your default type and options, then use ES6 shorthand syntax for object literals.

Here is a possible implementation:

const ctx1 = document.getElementById('myChart1'),
      ctx2 = document.getElementById('myChart2'),
      type = 'line',
      options = {
        scales: {
          x: {
            type: 'linear',
          },
          y: {
            type: 'linear',
          }
        }
      };

function addData(chart, data) {
  chart.data = { datasets: [] };
  chart.data.datasets.push(data);
  chart.update();
}

let chart1 = new Chart(ctx1, { type, options }); // <--- HERE

addData(chart1, {
  label: 'Dataset 1',
  data: [{ x: 0, y: 10 }, { x: 1, y: 20 }, { x: 2, y: 15 }]
});
  
let chart2 = new Chart(ctx2, { type, options }); // <--- HERE

addData(chart2, {
  label: 'Dataset 2',
  data: [{ x: 0, y: 7 }, { x: 1, y: 1 }, { x: 2, y: 3 }]
});
.chart-container {
  position: relative;
  height: 40vh;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<div class="chart-container">
  <canvas id="myChart1"></canvas>
</div>

<div class="chart-container">
  <canvas id="myChart2"></canvas>
</div>

EDIT

Below I put the same example with the spread syntax (...) as mentioned in my comment. This may be useful if you have some charts with specific options.

const ctx1 = document.getElementById('myChart1'),
      ctx2 = document.getElementById('myChart2'),
      type = 'line',
      options = {
        scales: {
          x: {
            type: 'linear',
          },
          y: {
            type: 'linear',
          }
        }
      };

function addData(chart, data) {
  chart.data = { datasets: [] };
  chart.data.datasets.push(data);
  chart.update();
}
    
let chart1 = new Chart(ctx1, { type, options: {
  ...options, // <--- HERE
  animations: {
    tension: {
      duration: 1000,
      easing: 'linear',
      from: 1,
      to: 0,
      loop: true
    }
  }
}});

addData(chart1, {
  label: 'Dataset 1',
  data: [{ x: 0, y: 10 }, { x: 1, y: 20 }, { x: 2, y: 15 }]
});
  
let chart2 = new Chart(ctx2, { type, options: {
  ...options, // <--- HERE
  plugins: {
    legend: {
      labels: {
        color: 'red'
      }
    }
  }
}});

addData(chart2, {
  label: 'Dataset 2',
  data: [{ x: 0, y: 7 }, { x: 1, y: 1 }, { x: 2, y: 3 }]
});
.chart-container {
  position: relative;
  height: 40vh;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<div class="chart-container">
  <canvas id="myChart1"></canvas>
</div>

<div class="chart-container">
  <canvas id="myChart2"></canvas>
</div>

Leave a comment