Question

I'm testing a d3js treemap from a blog. Please see the live jsbin here.

I want to control the filling color of each rect for each small area. I don't know where can I control the color of rect. I found the following part is setting the color.

 childEnterTransition.append("rect")
            .classed("background", true)
            .style("fill", function(d) {
                return color(d.parent.name);
            });

I try to remove the fill or change the color, the filling color is not working. For example I want to change all rect fill color to FFF, it is not working at all.

 childEnterTransition.append("rect")
            .classed("background", true)
            .style("fill", function(d) {
                return '#FFF';
            });
Was it helpful?

Solution

You're setting the fill colour twice three times -- once in the "enter" chain for new elements, and then again in the "update" chain for all elements, and then a third time during the zoom transition. If you're only changing one of those pieces of code, the others may be replacing your setting.

Enter code (from your bl.ocks page):

    childEnterTransition.append("rect")
        .classed("background", true)
        .style("fill", function(d) {
            return color(d.parent.name); //change this
        });

Update code: You can probably delete the entire update chain and just use the zoom function to update the values to the current zoom.

    childUpdateTransition.select("rect")
        .attr("width", function(d) {
            return Math.max(0.01, d.dx);
        })
        .attr("height", function(d) {
            return d.dy;
        })
        .style("fill", function(d) {
            return color(d.parent.name); //change this
        });

Zoom code:

    zoomTransition.select("rect")
        .attr("width", function(d) {
            return Math.max(0.01, (kx * d.dx));
        })
        .attr("height", function(d) {
            return d.children ? headerHeight : Math.max(0.01, (ky * d.dy));
        })
        .style("fill", function(d) {
            return d.children ? headerColor : color(d.parent.name); //change this
        });

Also, just to nitpick: Your "enter" selection (childEnterTransition) isn't actually a transition. If it was, there would be no point to setting the colour there and then re-setting it in update, because the update transition would just cancel the earlier transition. But because it isn't a transition, setting the colour there creates a starting value for the entering elements before you transition all the elements to the current value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top