22👍
You can make async AJAX calls no problem. It’s just important that you setup the chart only after the success callback fires. Otherwise, you’ll get issues with your canvas context not being defined. The first call to respondCanvas does the initial setup while the subsequent calls do the resizing.
Here is what works for me:
var max = 0;
var steps = 10;
var chartData = {};
function respondCanvas() {
var c = $('#summary');
var ctx = c.get(0).getContext("2d");
var container = c.parent();
var $container = $(container);
c.attr('width', $container.width()); //max width
c.attr('height', $container.height()); //max height
//Call a function to redraw other content (texts, images etc)
var chart = new Chart(ctx).Line(chartData, {
scaleOverride: true,
scaleSteps: steps,
scaleStepWidth: Math.ceil(max / steps),
scaleStartValue: 0
});
}
var GetChartData = function () {
$.ajax({
url: serviceUri,
method: 'GET',
dataType: 'json',
success: function (d) {
chartData = {
labels: d.AxisLabels,
datasets: [
{
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
data: d.DataSets[0]
}
]
};
max = Math.max.apply(Math, d.DataSets[0]);
steps = 10;
respondCanvas();
}
});
};
$(document).ready(function() {
$(window).resize(respondCanvas);
GetChartData();
});
If you want to insert a small delay between calls, you can use a timeout:
$(document).ready(function() {
$(window).resize(setTimeout(respondCanvas, 500));
GetChartData();
});
The delay will make your resizing more responsive in case you have a large dataset on your graph.
5👍
you can set that in chart.js
new Chart(context, {
type:"line",
labels: data.Dates,
datasets: [
{ fillColor: #404040, data: data.Users }
]
options: { responsive: false }
});
2👍
For those reading this in 2021:
Update for chart.js v3.x.x
Following updated answer for v3.x.x (which is not backwards compatible with v2.x.x)
First, answers to the 4 initial questions:
- The chart is not being resized on window resize.
- Is there better code to do this? I think I am repeating to much code.
- In Google the drawing is fast. In firefox sometimes it hangs for a while. Is anything wrong with my code?
- Should the request be async or not?
-
With current version, it should resize automatically, try it yourself running the snippet below and resizing the browser window.
-
The trick was to assign your chart to a variable
const myLineChart =
and then call simplymyLineChart.update()
when needed. Be aware to assign programmatically the labels and datasets again before callingmyLineChart.update()
, otherwise data changes would not reflect in chart. -
Should be fine now in firefox according to my testings.
-
Oh yes, absolutely async (either ajax or http-request with callback or promises).
// once the success function of your $.ajax request fires,
// put following code within your success-function
// for now, let's assume sample data
let data2 = {
"Dates" : [
"2021-08-02",
"2021-08-03",
"2021-08-04",
"2021-08-05",
"2021-08-06"
],
"Users": [
6,
4,
3,
8,
2
]
};
// Draw chart
const ctx = document.querySelector('canvas').getContext('2d');
const myLineChart = new Chart(ctx, {
type: 'line',
data: {
labels: data2.Dates,
datasets: [{
label: 'Users created',
data: data2.Users,
borderColor: 'green',
backgroundColor: '#404040',
fill: true,
animations: false // <-- now plural, instead of "animation" before
}]
}
});
// Redraw the chart with an added record
function updateData(event) {
event.target.disabled = true;
data2 = {
"Dates" : [
"2021-08-02",
"2021-08-03",
"2021-08-04",
"2021-08-05",
"2021-08-06",
"2021-08-07"
],
"Users": [
6,
4,
3,
8,
2,
12
]
};
// assign programmatically the datasets again, otherwise data changes won't show
myLineChart.data.labels = data2.Dates;
myLineChart.data.datasets[0].data = data2.Users;
myLineChart.update();
};
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!-- gets you the latest version of Chart.js, now at v3.5.0 -->
<button onclick="updateData(event)">add Data</button>
<canvas width="320" height="240"></canvas>
0👍
- Indeed
- Yes, I’ll give you an example.
- I dont see anything that might cause an issue. Except that window.resize might be firing rendering a new chart far more often then you want.
- No. (I don’t really know why, this is more coincidence.)
The code:
window.getVisitCounts = ($canvas) ->
url = Routes.visits_between_project_path($canvas.data('project-id'), {
format: "json",
start: $canvas.data('start'),
end: $canvas.data('end')
})
visits = []
days = []
$.ajax
url: url,
async: false,
dataType: "json",
type: "GET",
success: (data) - >
for point in data.chart.data
visits.push(point.visits)
days.push(point.date)
{
days: days,
visits: visits
}
window.createChartData = (raw) - > {
labels: raw.days,
datasets: [{
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
data: raw.visits,
}]
}
window.setupCanvas = ($canvas, data) - >
newWidth = $canvas.parent().width()
$canvas.prop
width: newWidth
height: 400
options = {
scaleOverride: true,
scaleSteps: 10,
scaleStepWidth: Math.ceil(Math.max.apply(Math, data.datasets[0].data) / 10),
scaleStartValue: 0
}
ctx = $canvas.get(0).getContext("2d")
new Chart(ctx).Line(data, options)
$ - > @canvas = $("#analytics-canvas")
if@ canvas.length != 0@ visits = window.createChartData(window.getVisitCounts(@canvas))
window.setupCanvas(@canvas, @visits)
$(window).on('resizeEnd', - >
setupCanvas(document.canvas, document.visits)
)
$(window).resize - >
if (@resizeTO)
clearTimeout(@resizeTO)
@resizeTO = setTimeout(- >
$(this).trigger "resizeEnd"
500
)
- [Chartjs]-Chart.js multiTooltip labels
- [Chartjs]-Charts.js Formatting Y Axis with both Currency and Thousands Separator