Search code examples
javascriptd3.jstreemap

Zoomable treemap in D3 v4


I'm trying to add zoom behaviour to my treemap in D3 v4 based on these examples: 1 and 2. It's built with HTML elements, rather than SVG and I have made it responsive by using percentage instead of pixel units.

It works great so far but now I'd like to zoom in to individual cells with a click until the last child has been reached. Then the click would go back to the root of the tree.

Here's my code so far: http://codepen.io/znak/pen/qapRkQ

I'm struggling with the zoom function that works in V4 and it's all over the place:

function zoom(d) {

    console.log('clicked: ' + d.data.name);

    x.domain([d.x0, d.x1]);
    y.domain([d.y0, d.y1]);

    var t = d3.transition()
        .duration(800)
        .ease(d3.easeCubicOut);

    chart
        .merge(cell)
        .transition(t)
        .style("left", function(d) { return x(d.x0) + "%"; })
        .style("top", function(d) { return y(d.y0) + "%"; })
        .style("width", function(d) { return x(d.x1 - d.x0) + "%"; })
        .style("height", function(d) { return y(d.y1 - d.y0) + "%"; });

    node = d; //?
    d3.event.stopPropagation(); //?
}

How do I update and transition elements with D3 v4?

Thanks for any hints!


Solution

  • After a long break I've noticed the mistake – wrongly placed parentheses here:

    .style("width", function(d) { return x(d.x1 - d.x0) + "%"; })
    .style("height", function(d) { return y(d.y1 - d.y0) + "%"; });
    

    It should be:

    .style("width", function(d) { return x(d.x1) - x(d.x0) + "%"; })
    .style("height", function(d) { return y(d.y1) - y(d.y0) + "%"; });
    

    Now the zoom functions properly.

    DEMO