d3 - 如何调整从完整的US clipPath绘制的单个状态映射的大小

时间:2016-11-05 18:44:23

标签: javascript d3.js topojson

我正在使用d3框架,我很好奇如何/是否可以制作一个单独的县级州地图,该地图是根据美国国家边界的clipPath创建的,而无需重新绘制从头开始绘图。

我尝试使用:

调整svg的宽度和高度attrbutes
d3.selectAll(".ismap").attr("width", width).attr("height", width * 1.5);
d3.selectAll(".ismap").selectAll("path").attr("d", path);
然而,这并没有返回预期的结果(在resize事件上显示了一小片土地)。

无论如何,这里是我所在的地方:

var $width = $(window).width();

var $height = $width * .8;
var width = $width,
    height = $height;
var projection = d3.geo.albers();
var path = d3.geo.path().projection(projection);
var svg = d3.select('.map-wrapper').append("svg").attr("width", width).attr("height", height).attr("class", "state-map ismap");

d3.json("map_json/us_county_land.json", function(error, us) {

    if (error) throw error;
    var states = topojson.feature(us, us.objects.states),
        state = states.features.filter(function(d) {
            return d.id === 36;
        })[0];

    projection.scale(1).translate([0, 0]);

    var b = path.bounds(state),
        s = .95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height),
        t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2];

    projection.scale(s).translate(t);

    svg.append("path").datum(topojson.mesh(us, us.objects.states, function(a, b) {
        return a !== b;
    })).attr("class", "mesh").attr("d", path);

    svg.append("path").datum(state).attr("d", path).attr("id", "land");

    svg.append("clipPath").attr("id", "clip-land").append("use").attr("xlink:href", "#land");

    svg.selectAll("path").data(topojson.feature(us, us.objects.counties).features).enter().append("path").attr("d", path).attr("data-county", function(d) {
        return d.id;
    }).attr("clip-path", "url(#clip-land").attr("class", "county").on('mouseover', function(d, i) {
        d3.select(this.parentNode.appendChild(this)).transition().duration(300)
            .style({
                'stroke-opacity': 1,
                'stroke': '#000',
                'stroke-width': '1px'
            });
    }).on('mouseout', function(d, i) {
        d3.select(this.parentNode.appendChild(this)).transition().duration(300)
            .style({
                'stroke-opacity': 1,
                'stroke': '#fff',
                'stroke-width': '1px'
            });
    });

});

1 个答案:

答案 0 :(得分:0)

这就是诀窍:

 svg.attr("viewBox", "0 0 " + width + " " + height ).attr("preserveAspectRatio", "xMinYMin")