0

I'm having trouble to get this to look nice when resizing. I'm sure there is some logic between the parent/child sizes and aspect I'm not understanding. If anyone could give me some pointers it would be much appreciated.

$(window).resize(function () {

    // Debounce our resizing
    var debounce = setTimeout(function() {

        // Only set attribute viewbox once   
        function setView(c, w, h) {
            if (!c.getAttribute("viewBox")) {
                var viewBox = "20 0 " + w + " " + h + "";
                c.setAttribute("viewBox", viewBox);
                c.setAttribute("preserveAspectRatio", "xMidYMid meet");
            }
        }

        // Reset previous timers
        clearTimeout(reset);
        clearTimeout(debounce);

        // Set variables
        var cal = d3.select("svg.RdYlGn")[0][0],
        parent = cal.parentElement,
        aspect = Math.round(parent.offsetWidth / parent.offsetHeight);
        var newHeight = (parent.offsetWidth / aspect),
            newWidth = parent.offsetWidth,
            oldHeight = cal.getAttribute("height") || cal.offsetHeight,
            oldWidth = cal.getAttribute("width") || cal.offsetWidth;

        // Set the viewbox
        setView(cal,oldWidth,oldHeight);

        // Set new dimensions for calendar
        cal.setAttribute("height", newWidth / aspect);
        cal.setAttribute("width", newWidth);

        // Make sure parent <div> behaves and follows with calendar                            
        var reset = setTimeout(function() {
            parent.setAttribute("width", cal.getAttribute("width"));
            parent.setAttribute("height", cal.getAttribute("width")/aspect);
            }, 500);
        }, 300);

    });

1 Answers1

0

Instead of sweating over viewBox and preserveAspectRatio on $(window).resize just fetch the parent height and width dynamically each time the window is resized:

 var containerWidth = $("#yourChartId").parent().width(); // gets immediate parent width
 var containerheight = $("#yourChartId").parent().height();// gets immediate parent height
 var margin = {top: 15, right: 15, bottom: 20, left: 40},
 width = containerWidth- margin.left - margin.right,
 height = containerheight - margin.top - margin.bottom;
SiddP
  • 1,603
  • 2
  • 14
  • 36