1👍
✅
You can use segment
styling that update dynamicly when you add new data:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'orange',
fill: true,
segment: {
backgroundColor: (ctx) => (ctx.p0.parsed.y > ctx.p1.parsed.y ? 'red' : 'teal')
}
}]
},
options: {}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
const c = new Chart(ctx, options);
document.getElementById('add').addEventListener('click', () => {
c.data.labels.push(c.data.labels.length);
c.data.datasets[0].data.push(c.data.datasets[0].data[c.data.datasets[0].data.length - 1] + 10)
c.update()
});
document.getElementById('subb').addEventListener('click', () => {
c.data.labels.push(c.data.labels.length);
c.data.datasets[0].data.push(c.data.datasets[0].data[c.data.datasets[0].data.length - 1] - 10)
c.update()
});
<body>
<button id="add">
Add 10
</button>
<button id="subb">
Subtract 10
</button>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
</body>
Source:stackexchange.com