I'm new to Javascript and now I'm tasked to display charts with Chart.js. I did grouping in Python and used Flask to build the web app. However, my chart is somehow not displayed and I'm not sure why.
HTML
<canvas id="barchart2" width="600" height="400"></canvas>
JS
<script>
var config = {
type: 'bar',
labels : [
"52",
"51",
"54",
"53",
"46",
"82",
"57",
"48",
"50",
"56",
],
datasets : [
{
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
data : [
611,
18,
11,
10,
9,
8,
6,
3,
2,
2,
]
}
]
},
options: {
legend: {
display: true,
},
title: {
display: true,
text: 'Top 10 District in Singapore',
}
},
};
window.onload = function() {
var ctx = document.getElementById("barchart2").getContext("2d");
window.myBar = new Chart(ctx, config);
};
</script>
When I used this JS instead
var barData = {
labels : [{% for item in lbl1 %}
"{{item}}",
{% endfor %}],
datasets : [
{
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
data : [{% for item in val1 %}
{{item}},
{% endfor %}]
}
]
}
// get bar chart canvas
var mychart = document.getElementById("barchart2").getContext("2d");
// draw bar chart
new Chart(mychart).Bar(barData);
It worked perfectly (note: without options. I tried to add options, but the options doesn't show although the charts still appears. That's why I wanna change to this format instead). But when I use the window.onload function, the chart doesn't appear at all.
Would appreciate your help. Thanks!