当从websocket收到日期时,我正试图使用.update()方法更新Line chart.js的数据,但这不起作用,我无法解决问题。这是我的代码:
<!doctype html>
<html>
<head>
<title>Line Chart</title>
<script src="js/Chart.js"></script>
<script type="text/javascript">
if ("WebSocket" in window) {
var ws = new WebSocket("ws://localhost:8888/ws");
ws.onopen = function() {
ws.send("data");
};
ws.onmessage = function(evt) {
var received_msg = JSON.parse(evt.data)
alert(received_msg[0]);
alert(received_msg[1]);
lineChartData.labels = received_msg[0];
lineChartData.datasets[0].data = received_msg[1];
lineChartData.update();
};
ws.onclose = function() {
// websocket is closed.
console.log("Connection is closed...");
};
} else {
// The browser doesn't support WebSocket
console.log("WebSocket NOT supported by your Browser!");
}
</script>
</head>
<body>
<div style="width:70%">
<div>
<canvas id="canvas" height="450" width="800"></canvas>
</div>
</div>
<script>
var lineChartData = {
labels: [],
datasets: [{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: []
}]
}
var options = {
responsive: true,
scaleShowGridLines: false,
scaleLineColor: "rgba(0,0,0,.1)",
}
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, options);
</script>
</body>
</html>
这是我想更新图表的部分:
ws.onmessage = function(evt) {
var received_msg = JSON.parse(evt.data)
alert(received_msg[0]);
alert(received_msg[1]);
lineChartData.labels = received_msg[0];
lineChartData.datasets[0].data = received_msg[1];
lineChartData.update();
};
从警报输出中,我收到了格式良好的良好数据,但更新不起作用。
你能帮我吗?
问题是您正在更新数据"lineChartData",但您想在图表上调用update()
所以
ws.onmessage = function(evt) {
var received_msg = JSON.parse(evt.data)
alert(received_msg[0]);
alert(received_msg[1]);
lineChartData.labels = received_msg[0];
lineChartData.datasets[0].data = received_msg[1];
window.myLine.update(); //<-- magic
};
如果您绘制的图表不是chart.js例如,ccchart
http://jsfiddle.net/UkdvS/602/
https://github.com/toshirot/ccchart
var chartdata81 = {
"config": {
"title": "WebSocket Line Chart",
"subTitle": "realtime",
"bg": "#666",
"type": "line",
"xLines": [{
"useRow":1,
"color":"rgba(250,250,250,0.7)"
}]
},
"data": [
["year"],
["data1"],
["data2"]
]
};
ccchart
.init('hoge', chartdata81)
.ws('ws://ccchart.com:8016')
.on('message', ccchart.wscase.oneColAtATime);
此时WebSocket数据格式如下:
["23:41:47",58,41]
["23:41:47",30,46]
["23:41:47",7,35]
["23:41:47",46,34]
["23:41:47",59,41]
["23:41:47",95,47]
["23:41:47",22,40]
["23:41:47",73,35]
・・・・
・・・・
・・・・
@请参阅qiita.com/toshirot/items/a461cdc8c2079d9b8530(日语)