Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize Morris.js chart on changes to container dimensions

I try to put Morris js donut chart in the flex container with 2 flex items, I expect that chart in flex: 1 container will resize, but it does not. Does anyone know how to make the chart to be responsive in flex item?

Here is my example example try to resize it

JS:

$(function () {
    Morris.Donut({
        element: 'container',
        resize: true,
        data: [
            {label: "Download Sales", value: 12},
            {label: "In-Store Sales", value: 30},
            {label: "Mail-Order Sales", value: 20}
        ]
    });

CSS:

html, body {
height: 100%;
margin: 0;
}

body {
    display: -webkit-flex;
}

#container {
  flex: 1;
}

.flex1 {
  flex: 1;
  border: 1px solid red;
}
like image 614
sonya Avatar asked Feb 17 '16 23:02

sonya


People also ask

How do you change the size of ChartJS?

The chart can also be programmatically resized by modifying the container size: chart.canvas.parentNode.style.height = '128px'; chart.canvas.parentNode.style.width = '128px'; Copied! Note that in order for the above code to correctly resize the chart height, the maintainAspectRatio option must also be set to false .

How do I make a line chart responsive?

To make chart responsive just set responsive key to true inside lineChartOptions. Also, remember to remove :width and :height properties from the element and make the wrapper element responsive via css/scss.


1 Answers

Add a $(window).on('resize', ...) event handler then call the graphs redraw() function.

If there is a dynamic UI element that causes the layout to "flex" based on user input, you will want to call redraw() there as well as there is no way to directly listen for the resizing of a div.

Here is your fiddle, updated with the fix.

jsFiddle

Also, here is a note from a developer of Morris.js

Note: I suggest you call redraw() sparingly as it's quite an expensive operation. Try using a setTimeout trick or similar to avoid calling it for intermediate resize events.

A way to heed this advice is below:

$(window).on('resize', function() {
   if (!window.recentResize) {
      window.m.redraw();
      window.recentResize = true;
      setTimeout(function(){ window.recentResize = false; }, 200);
   }
});

Here is a fiddle with this implemented:

jsFiddle

like image 52
thedarklord47 Avatar answered Oct 04 '22 16:10

thedarklord47