Charts rendered in hidden DIVs will not display until browser resize
If there is already a work around for this, please let me know, but here is my use case / issue.
I am using foundation's tabset directive to build up tabs and their corresponding containers. I have some the chart.js graphs being defined inside a hidden container; therefore, the charts have no container width or height when it comes to rendering the graphs.
Would there be a way to achieve this? Could you potentially add in a "reset" watch to the angular-chart.js which will destroy and recreate the chart?
This looks similar to #17 which itself is same as https://github.com/nnnick/Chart.js/issues/512.
Could you just set the data when the tab is shown/active? That will draw the chart when the tab is first shown.
Check out my fork (dont know how to link to it, my first contribution on github). You can now send a angular broadcast '$reload' to repaint the graphs.
Cool, why not submitting a PR? ;)
https://help.github.com/articles/using-pull-requests/
Links to a PR is as simple as putting a link to it in the comment.
I've added @leonetnl 's changes to my personal copy of angular-chartjs, and the broadcast works, but it doesn't seem to redraw the chart. I know this is more of a Chart.js issue, but I've been pulling my hair out with it for a few hours now and can't get it working. Right now I'm calling resetChart(chart) in the broadcast $reload function, which seems to do exactly what the chartjs solution says to do (destroy old chart and create new one)
If the original chart is drawn successfully, I can call chart update/create/whatever. However, if the initial draw call comes when the div is hidden, it doesn't draw. I get this error - Uncaught IndexSizeError: Failed to execute 'arc' on 'CanvasRenderingContext2D': The radius provided (-0.5) is negative.
No matter how I try to update the chart - whether I update it, destroy it, create a new one, it just doesn't work. Its almost like the canvas permanently fails the draw, and refuses to reload unless part or all of the html itself is reloaded.
I'm willing to integrate the changes and submit a pull request myself, but I can't get it drawing correctly.
So I've figured out the cause - although not a solution (at least for me). It looks like the elem variable in the directive is never updated when the element changes height, so it retains the 0px height it gets when the div is not visible. I'm personally using angular-ui bootstrap tabs, so when I tab back to the original tab, the elem variable has a 0px height, although the actually element it is referring to no longer does. That is why the destroy/create method recommended for chartjs doesn't work, even if its called when the div is visible.
my only solution so far to this has been to use a directive with the $compile injector and delete and repaint the canvas element in the dom when it becomes visible maybe you guys can try a similar work arround
The same problem encountered, it seems that this issue not resolved yet.
Personally, I transfer the content with chart (which should place between tab) into another standalone <div></div> container, and use ng-show and tab select(), deselect() to control the visibility.
<div class="container" style="width: 60%;" ng-controller="MainCtrl">
<tabset justified="true">
<tab heading="chart" select="select()" deselect="deselect()">
</tab>
<tab heading="info">
The beautiful movie "Whiplash"!
</tab>
</tabset>
<div ng-show="chartTabShow">
<canvas id="line" class="chart chart-line" data="data" labels="labels" series="series">
</canvas>
</div>
</div>
$scope.select = function() {
$scope.chartTabShow = true;
};
$scope.deselect = function() {
$scope.chartTabShow = false;
};
To be honest, it's not good solution, even for me. I consider this way as temporary solution for urgent situation, not recommended.
Have you tried just initialising the data when you select the tab?
$scope.select = function() {
$scope.data = savedData;
};
@jtblin, I tried that - unfortunately it did not work as well.
This problem reminds me to an "ng-grid" inside a "bootstrap-ui tab".
I typically solve that problem with an uggly $(window).resize() when the tab is selected...
eg:
$scope.ngGridFIx = function() {
$(window).resize()
}
<tab select="ngGridFix()"> ... </tab>
BUT HERE...... the $(window).resize() is not working for me!... and it is weird because if I manually (not programatically) resize the window, the chart is fixed.
So,... what can I do?
Side note: this time my problem is not with a bootstrap tab but a chart in a bootstrap modal
Here is a jsbin for @bornkiller's solution: http://jsbin.com/sopupij/1/edit?html,js,output. Not ideal but it works.
And here is an example by delaying setting the data until the tab is selected + wrapped in a $timeout: http://jsbin.com/sopupij/3/edit. Not ideal either but...
Thanks @jtblin The $timeout solution worked well when the chart is in a bootstrap-ui modal, but I had to add 100ms as the delay parameter (if not, the result was random: it worked sometimes)
Several have mentioned the solution of setting the data after the tab/accordion/previously-hidden-div is brought into focus. This works for me, but only after setting a timeout (in my case 1 sec). Here are the main things to keep in mind:
- since you are using bootstrap tabs or accordion, and each panel has it's own scope, you cannot simply place the data for the chart directly onto your $scope in the controller. I set up my data like this:
$scope.chartSettings = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
series: ['Series A', 'Series B'],
onClick: function (points, evt) {
console.log(points, evt);
}
}
the HTML....
<canvas id="line" class="chart chart-line" data="chartSettings.data" labels="chartSettings.labels" legend="true" series="chartSettings.series" options="chartSettings.options" click="chartSettings.onClick"></canvas>
- Since the directive for the chart watches various pieces of data and resets the chart when that data changes, you can set the data element for the chart after the tab/accordion comes into focus...like this
//a snippet of the HTML for the accordion...
<accordion-group is-open="false">
<accordion-heading>
<div ng-click="opened(1)">
Chart <i class="pull-right glyphicon" ng-class="{'glyphicon-chevron-down': groups[1].open, 'glyphicon-chevron-right': !groups[1].open}"></i>
</div>
.... etc....
$scope.opened = function (groupIndex) {
$scope.groups[groupIndex].open = !$scope.groups[groupIndex].open;
if (groupIndex === 1) { //this is the accordion that holds the chart
$timeout(updateChart, 1000);
}
return true;
}
var updateChart = function() {
$scope.chartSettings.data = [
[65, 59, 80, 81, 56, 55, 40],
[28, 48, 40, 19, 86, 27, 90]
];
}
The timeout was necessary as we need to wait until the accordion or the tab has a true height...1 second seemed to work for me.
@germanger
You can use this instead
$scope.ngGridFIx = function() {
window.dispatchEvent(new Event('resize'));
}
It worked for me
Any update on this? I'm also having trouble trying to draw a chart in a "ng-hide" hidden situation to no avail.
I don't think that can be easily fixed unfortunately otherwise that would be already done. If the workaround described above doesn't work for you, another option is to set responsive to false in the options and set a height and width directly on the canvas.
+1
@jtblin Your workaround in the example does not work if you select "info" tab, then resize the display area and then switch to "chart" tab. The graph is not displayed. In my ionic app, I think I solved this issue with
$timeout(function(){ window.dispatchEvent(new Event('resize')); });
when the chart tab becomes active, but now the chart is not visible if I enter an app on another page and then navigate to the chart page
my final solution, which may impact performance, is to introduce a new event into the directive:
scope.$on('resizeChart', function () {
var chartType = type || scope.chartType;
if (chart){chart.destroy();}
chart = createChart(chartType, scope, elem);
});
and then broadcast this event in the controller, when the tab becomes active:
$timeout(function(){ $scope.$broadcast('resizeChart'); });
I had to update the createChart function in the angular-chart.js which stopped the ChartJs.Chart() function from zeroing the size of the canvas when it wasn't visible.
This is what I inserted
if (ctx.canvas['offsetHeight'] == 0)
return;
This is the full function
function createChart (type, scope, elem) {
if (! scope.data || ! scope.data.length) return;
scope.getColour = typeof scope.getColour === 'function' ? scope.getColour : getRandomColour;
scope.colours = getColours(type, scope);
var cvs = elem[0], ctx = cvs.getContext('2d');
if (ctx.canvas['offsetHeight'] == 0)
return;
var data = Array.isArray(scope.data[0]) ?
getDataSets(scope.labels, scope.data, scope.series || [], scope.colours) :
getData(scope.labels, scope.data, scope.colours);
var options = angular.extend({}, ChartJs.getOptions(type), scope.options);
var chart = new ChartJs.Chart(ctx)[type](data, options);
scope.$emit('create', chart);
['hover', 'click'].forEach(function (action) {
if (scope[action]) cvs[action === 'click' ? 'onclick' : 'onmousemove'] = getEventHandler(scope, chart, action);
});
if (scope.legend && scope.legend !== 'false') setLegend(elem, chart);
return chart;
}