我正在尝试通过Charts.js上的教程制作图形。但是当我运行html文件时,该图没有显示。
我按照教程中的说明在脚本中编写了js代码,但没有用。然后将js代码放入一个函数中,但也没有起作用。
如果您可以查看是否可以将js源代码仅放在脚本或函数中,那就太好了。我必须在显示数据库表的网页顶部显示图表。
教程网络链接,第一个示例:https://www.sitepoint.com/introduction-chart-js-2-0-six-examples/
这是我的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Weather Update</title>
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script>
function dspChrt() {
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
datasets: [{
label: 'apples',
data: [12, 19, 3, 17, 6, 3, 7],
backgroundColor: "rgba(153,255,51,0.4)"
}, {
label: 'oranges',
data: [2, 29, 5, 5, 2, 3, 10],
backgroundColor: "rgba(255,153,0,0.4)"
}]
}
});
}
</script>
</head>
<body onload="dspChrt();">
<div class="container">
<h2>Chart Demo</h2>
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</body>
</html>
答案 0 :(得分:1)
请使用此代码
var canvas = document.getElementById('myChart');
var data = {
labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
datasets: [{
label: 'apples',
data: [12, 19, 3, 17, 6, 3, 7],
backgroundColor: "rgba(153,255,51,0.4)"
}, {
label: 'oranges',
data: [2, 29, 5, 5, 2, 3, 10],
backgroundColor: "rgba(255,153,0,0.4)"
}]
};
var option = {
scales: {
yAxes:[{
stacked:true,
gridLines: {
display:true,
color:"rgba(255,99,132,0.2)"
}
}],
xAxes:[{
gridLines: {
display:true
}
}]
}
};
var myBarChart = Chart.Line(canvas,{
data:data,
options:option
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<div class="container">
<h2>Chart Demo</h2>
<div>
<canvas id="myChart" width="400" height="200"></canvas>
</div>
</div>