I'd like to use Chart.js to create stunning charts into a webpage.
Following the documentation, I wrote the code as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Chart.js demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js" type="text/javascript"></script>
</head>
<body>
<script>
var pieData = [
{
value: 20,
color:"#878BB6"
},
{
value : 40,
color : "#4ACAB4"
},
{
value : 10,
color : "#FF8153"
},
{
value : 30,
color : "#FFEA88"
}
];
// Get the context of the canvas element we want to select
var countries= document.getElementById("countries").getContext("2d");
new Chart(countries).Pie(pieData);
</script>
<h1>Chart.js Sample</h1>
<canvas id="countries" width="600" height="400"></canvas>
</body>
</html>
Which is the reason why the chart doesn't appear?
在canvas元素外添加一个div:
<div><canvas id="countries" width="600" height="400"></canvas></div>
First, you have to put your script after the canvas declaration. After that, delete the pie options (or define them).
<html>
<head>
<meta charset="utf-8"/>
<title>Chart.js demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js" type="text/javascript"></script>
</head>
<body>
<h1>Chart.js Sample</h1>
<canvas id="countries" width="600" height="400"></canvas>
<script>
var pieData = [
{
value: 20,
color:"#878BB6"
},
{
value : 40,
color : "#4ACAB4"
},
{
value : 10,
color : "#FF8153"
},
{
value : 30,
color : "#FFEA88"
}
];
// Get the context of the canvas element we want to select
var countries= document.getElementById("countries").getContext("2d");
new Chart(countries).Pie(pieData);
</script>
</body>
pieOptions is null :) just remove it from your .Pie() call.
And keep your browser script console open, so you can see all the valuable output it provides you :)
Such a problem occurred to me because I didn't put a comma after the {{ data }}
Wrong[{% for data in years %} '{{ data }}' {% endfor %}]
Right one[{% for data in years %} '{{ data }}', {% endfor %}]
$(document).ready(function(){
var ctx = document.getElementById('myChart').getContext('2d');
console.log("context",ctx);
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [{% for data in years %} '{{ data }}', {% endfor %}], //loop through queryset,
datasets: [{
label: 'Value',
data: [{% for data in values %} '{{ data }}', {% endfor %}], //loop through queryset
fill: false,
borderColor: [
'rgba(75, 192, 192, 1)',
],
tension: 0.1,
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.