當前我正在嘗試以編程方式爲股票報告網站創建多個圖表。我有一個配置是這樣定義的..Chartjs圖表更新後使用相同顏色繪製
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()}
}
};
然後我創建一個圖表數組,然後可以稍後更新。
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);
}
每個圖表應該具有與它相關聯的隨機顏色,但是圖表最終被完全相同的顏色。
這裏也是圖表的更新代碼。
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();
}