Currently I am trying to programatically create multiple charts for a stock reporting website. I have a config which is defined as so..
let chartConfig = {
// The type of chart we want to create
type: "line",
// The data for our dataset
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "Test",
//default colour
borderColor: "rgb(255, 99, 132)",
data: [],
fill: false
}]
},
// Configuration options go here
options: {
responsive: true,
//Don't want to be able to remove the data.
legend: {onClick: (e) => e.stopPropagation()}
}
};
I am then creating an array of charts that can then be updated later on.
let chartArray = [];
let chartIds = [];
for(let context of document.getElementsByTagName("canvas")){
let drawingContext = context.getContext("2d");
let ticker = drawingContext.canvas.id;
let localConfig = chartConfig;
localConfig.data.datasets[0].borderColor = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
chartArray.push({ticker: ticker, chart: new Chart(drawingContext, localConfig)});
chartIds.push(ticker);
}
Each chart should have a random colour associated with it, however the charts end up being the exact same colour.
Here is also the update code for the chart.
socket.on("my_response", function(msg) {
for(let packet of msg){
addData(chartArray.find(chart => chart.ticker === packet.ticker).chart, packet.ticker, packet.data)
}
});
function addData(chart, label, data) {
console.log(chart);
chart.data.datasets[0].label = label;
chart.data.datasets.forEach((dataset) => {
dataset.data = data
});
chart.update();
}