score: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
)
score: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>
score: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 }
});
score: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.
Source: stackoverflow.com
Related Query
- Draw a Chart.js with ajax data and responsive. A few problems and questions
- ChartJS - Draw chart with label by month, data by day
- Can we draw a Line Chart with both solid and dotted line in it?
- ChartJS (React) Line Chart - How to show single tooltip with data and labels from 3 (multiple) dataset?
- Trying to load a chart with chart.js, through ajax and php
- How to get chart from data points (arrays) with inconsistent time intervals and chart.js?
- Doughnut Chart not displaying data with Chart Js and Backbone js
- How to reuse a Chartjs Chart component in with different Data and get past the **Canvas is already in use** error?
- Real-time line chart with ChartJS using Ajax data
- Send data from php to chart with ajax
- Chart.js combined line and bar chart with differing data points
- Draw a Chart.js with data retrieved through ajax call
- Chart Piechart in only show percentage on hover but it shows data and label with percentage both i just want to show percentage only percentage
- how to write labels along with data on top and bottom of each stack in bar chart
- How to render multiple Chart.JS charts on the same page with AJAX data and variables
- I am using chart js to draw a chart. I did everything right but i don't know why the x axis and y axis label is not comming in chart. code below
- Chartjs create chart with big data and fixed labels
- Multiple axis line chart with Chart.js and JSON data from Google Sheet
- How can I build some chart with Chart.js and ng2-charts using an array of revenus & budgets per month date as Data source?
- Unable to get chartjs to draw a chart with dynamic data (variable not hardcoded)
- Use multi data to draw chart with chartjs
- Chartjs random colors for each part of pie chart with data dynamically from database
- line chart with {x, y} point data displays only 2 values
- Chartjs 2 - Stacked bar and unstacked line on same chart with same y axis
- Chart.js Mixed Bar and Line chart with different scales
- How do I draw a vertical line on a horizontal bar chart with ChartJS?
- Problem for display a chart with Chart.js and Angular
- Chart.js - Draw bar chart with multiple labels
- Show X axis on top and bottom in line chart rendered with Chart.js 2.4.0
- Chart.js Timeseries chart - formatting and missing data values
More Query from same tag
- Trying to have Doughnut chart with dql result chartjs
- How to get data of json file for chart.js diagram
- Where is the appropriate place to instantiate a javascript widget/chart/utility when using angular.js?
- Chart JS display Data Value on the top of the Bar
- Display Time In Y Axis - Bubble Chart
- chartjs: How to plot multi-line chart with irregular intervals
- Combining charting with the map
- ChartJS - How to increase the maximum degree of label rotation on x-axis?
- Chart.js axes label font size
- how to create a bar chart with php data variables
- How to access all data in a function with ChartJs?
- Chart.js PolarArea Chart. Changing the labels to a 45 degree angle
- How to use 'time' (data from database, data type: timestamp ) for plotting graph in Chart JS
- math.max() doesn't work in IE
- How to display a progress over time in one horizontally stacked bar with chartjs
- ChartJS - rolling twenty minute view
- ChartJS 2.6 - Bar chart fixed height scrollable-X
- Chartjs multiple barcharts corresponding to one label
- How to sort MMMYY on Chart.Js and display the values that match the month?
- Adding a label to a doughnut chart in Chart.js shows all values in each chart
- Problem with script src for Chart.js. The CDN for Chart.js funtions fine, so my code is ok. Somehow I'm not linking the file correctly
- Is there any method to map or represent API data to Chart in ReactJS?
- Chart.JS Bar Chart Throwing Error About Missing )
- Chartjs tooltips disappear when calling Chart.update
- setting QuickCharts color
- Update a chartjs by javascript function
- Styling problems with Chart.Js
- How to get Max Values of a Multidimensional Array for 30 Days
- How to shade a portion of the background of ChartJS bubble chart?
- JavaScript Chart.js - Custom data formatting to display on tooltip