JSFiddle - React, Tailwind, and code Playground
by beneverard
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>
JavaScript
var ctx = document.getElementById('myChart').getContext('2d');
// add the multi style line type
Chart.defaults.multistyleline = Chart.defaults.line;
Chart.controllers.multistyleline = Chart.controllers.line.extend({
draw: function(ease) {
var meta = this.getMeta(),
points = meta.data || [],
lineStyles = this.getDataset().lineStyles || [],
area = this.chart.chartArea,
originalDatasets = meta.dataset._children.filter(function(data) {
return !isNaN(data._view.y);
});
// if there is no line styles, draw using the line function
if ( ! lineStyles.length ) {
Chart.controllers.line.prototype.draw.call(this, ease);
return;
}
lineStyles.forEach((lineStyle, index) => {
// loop through the line styles and assign each individual style…
Object.keys(lineStyle).forEach(function(key) {
// …just so long as it isn't the start value
if (key !== 'start') {
meta.dataset._view[key] = lineStyle[key];
}
});
// set the default end position to the end of the points array…
let end = points.length;
// …but if we're about to follow up with another style, set the end to the start of the next
if (typeof lineStyles[index + 1] !== 'undefined') {
end = lineStyles[index + 1].start + 1;
}
// set the initial style
meta.dataset._children = originalDatasets.slice(lineStyle.start, end);
meta.dataset.draw();
});
meta.dataset._children = originalDatasets;
points.forEach(function(point) {
point.draw(area);
});
}
});
var chart = new Chart(ctx, {
type: 'multistyleline',
data: {
labels: ['Apr', 'May ', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar'],
datasets: [{
data: [100, 200, 300, 400, 500, 600, 700, 900, 1100, 1300, 1600, 1900],
pointRadius: 0,
fill: false,
borderColor: '#B363BE',
label: 'Turnover',
lineStyles: [{
start: 0,
borderDash: false
}, {
start: 5,
borderDash: [10, 5]
}]
}]
}
});