testing chartjs
Update: 30 June 2020 I checked this code, and it was broken all fixed now. The issue with the demo included on the main site is that it was trying to run the chart js before the chart library was loaded. you have to create the chart when the document is ready to fix this. The window onload does not work either. has to be a document ready. You can use the plain javascript version of this or the jquery if you want to rely on that.
Seeing how easy it is too add some chart.js charts using the getting started documentation.
Install via CDN here. Hmm.. do i need the bundle and the normal one? I guess i do?
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js"></script>
I think you only need to add one of the chart js's one of them comes bundled with moment js something to do with the chart labels.
add the chart
using the provided demo was giving me the error:
(index):244 Uncaught TypeError: Cannot read property 'getContext' of null
at (index):244
this was due to the chart script not being loaded when the initial kick off script is run, so adding a window.onload function and then adding the chart into this function should fix this
window.onload = function() {
create_chart();
}
Using window.onload did not allow for the script to load, so using a DOMContentLoaded event listener fixes this issue.
document.addEventListener("DOMContentLoaded", function(event) {
create_chart();
});
HTML
<canvas id="myChart" width="400" height="400"></canvas>
Scripts
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha256-R4pqcOYV8lt7snxMQO/HSbVCFRPMdrhAFMH+vr9giYI=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.css" integrity="sha256-aa0xaJgmK/X74WM224KMQeNQC2xYKwlAt08oZqjeF0E=" crossorigin="anonymous" />
Javascript
window.onload = function() {
create_chart();
}
document.addEventListener("DOMContentLoaded", function(event) {
create_chart();
});
function create_chart() {
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}