Keep D3 objects constant on the map while zooming in / out

I am following the example from http://bl.ocks.org/d3noob/raw/5193723/

The loops drawn in the example grow in size as you zoom in. I can't figure out how the size of the circles can be kept the same.

Any ideas?

Edit1 : Any ideas on how to keep the arc radius constant in radii. I figured out how to keep the circles in a constant radius like below:

            g1.append("circle")
                .attr("cx", 200)
                .attr("cy", 200)
                .attr("r", 10)
                .style("fill", "red");

        var zoom = d3.behavior.zoom().on("zoom", function () {

                g1.selectAll("circle")
                    .attr("transform", "translate(" + d3.event.translate.join(",") + ")scale(" + d3.event.scale + ")")
                    .attr("r", function(d) {
                        return 10/d3.event.scale;
                    });
            });

      

Likewise, I have arcs of a pie chart that I want to maintain the size while scaling:

                    var r = 4;
                    var p = Math.PI * 2;

                    var arc = d3.svg.arc()
                        .innerRadius(r - 2)
                        .outerRadius(r - 1)
                        .startAngle(0)
                        .endAngle(p * d.value1);
                    var arc2 = d3.svg.arc()
                        .innerRadius(r - 3)
                        .outerRadius(r - 2)
                        .startAngle(0)
                        .endAngle(p * d.value2);

                   var projection = d3.geo.mercator()
                        .center([0, 5])
                        .scale(200)

                    var translate = "translate(" + projection([77, 13])[0] + ", " + projection([77, 13])[1] + ")";
                    g.append("path")
                        .attr("d", arc)
                        .attr("fill", "maroon")
                        .attr("transform", translate);
                    g.append("path")
                        .attr("d", arc2)
                        .attr("fill", "green")
                        .attr("transform", translate);

      

Any suggestions on how to keep arc type paths to maintain the same size?

+1


source to share


1 answer


You will need to add additional handling for the zoom event handler. Set the radii of the circle as their nominal value (5) divided by the scaling factor ( zoom.scale()

). Thus, when scaling down, the result will have a constant visible size. Something like:



var zoom = d3.behavior.zoom()
    .on("zoom",function() {
        g.attr("transform","translate("+ 
            d3.event.translate.join(",")+")scale("+d3.event.scale+")");
        g.selectAll("circle")
            .attr("d", path.projection(projection))
            .attr("r", 5/zoom.scale());
        g.selectAll("path")  
            .attr("d", path.projection(projection)); 
    });

      

+3


source







All Articles