如何调整D3中某个点的缩放大小?

时间:2013-02-28 16:56:15

标签: d3.js zoom transform

这可能是“你做错了”的经典案例,但我迄今为止所有的搜索都没有得到任何帮助。

这是我的情景:

我正在使用albersUSA地图投影与国家和县GeoJson文件一起绘制所有内容。

我还有一个自创的“城市”文件,其中包含每个州的主要城市。坐标是准确的,一切都很好。

enter image description here

当用户点击给定状态时,我隐藏所有状态形状,然后计算使该状态的县形状适合我的视口所需的变换。然后,我将该变换应用于所有必要的县形状,以获得“缩放”视图。我的代码如下:

function CalculateTransform(objectPath)
{
   var results = '';

   // Define bounds/points of viewport
   var mapDimensions = getMapViewportDimensions();
   var baseWidth = mapDimensions[0];
   var baseHeight = mapDimensions[1];

   var centerX = baseWidth / 2;
   var centerY = baseHeight / 2;

   // Get bounding box of object path and calculate centroid and zoom factor
   // based on viewport.
   var bbox = objectPath.getBBox();
   var centroid = [bbox.x + bbox.width / 2, bbox.y + bbox.height / 2];
   var zoomScaleFactor = baseHeight / bbox.height;
   var zoomX = -centroid[0];
   var zoomY = -centroid[1];

   // If the width of the state is greater than the height, scale by
   // that property instead so that state will still fit in viewport.
   if (bbox.width > bbox.height) {
      zoomScaleFactor = baseHeight / bbox.width;
   }

   // Calculate how far to move the object path from it's current position to
   // the center of the viewport.
   var augmentX = -(centroid[0] - centerX);
   var augmentY = -(centroid[1] - centerY);

   // Our transform logic consists of:
   // 1. Move the state to the center of the screen.
   // 2. Move the state based on our anticipated scale.
   // 3. Scale the state.
   // 4. Move the state back to accomodate for the scaling.   
   var transform = "translate(" + (augmentX) + "," + (augmentY) + ")" +
                 "translate(" + (-zoomX) + "," + (-zoomY) + ")" +
                 "scale(" + zoomScaleFactor + ")" +
                 "translate(" + (zoomX) + "," + (zoomY) + ")";

   return results;
}

...和绑定功能

// Load county data for the state specified.
d3.json(jsonUrl, function (json) {
    if (json === undefined || json == null || json.features.length == 0) 
    {
       logging.error("Failed to retrieve county structure data.");
       showMapErrorMessage("Unable to retrieve county structure data.");
       return false;
    }
    else 
    {
       counties.selectAll("path")
                .data(json.features)
                .enter()
                   .append("path")
                      .attr("id", function (d, i) {
                         return "county_" + d.properties.GEO_ID
                      })
                      .attr("data-id", function (d, i) { return d.properties.GEO_ID })
                      .attr("data-name", function (d, i) { return countyLookup[d.properties.GEO_ID] })
                      .attr("data-stateid", function (d, i) { return d.properties.STATE })
                      .attr("d", path);

        // Show all counties for state specified and apply zoom transform.
        d3.selectAll(countySelector).attr("visibility", "visible");
        d3.selectAll(countySelector).attr("transform", stateTransform);

        // Show all cities for the state specified and apply zoom transform
        d3.selectAll(citySelector).attr("visibility", "visible");
        d3.selectAll(citySelector).attr("transform", stateTransform);
    }
});

enter image description here

这在这里工作正常,除了非常小的状态,缩放系数要大得多,并且圆圈会被分散。

enter image description here

即使转换发生后,有没有办法强制点的大小为固定大小(比如15px半径)?

2 个答案:

答案 0 :(得分:6)

对于您不想缩放的内容,只需将它们除以“缩放”即可。就我而言,

var zoom = d3.behavior.zoom()
    .on("zoom",function() {
        g.attr("transform","translate("+d3.event.translate.join(",")+")scale("+d3.event.scale+")");

        g.selectAll(".mapmarker")  
        .attr("r",6/d3.event.scale)
        .attr("stroke-width",1/d3.event.scale);

});

答案 1 :(得分:5)

这种情况正在发生,因为您正在设置缩放变换而不是缩放位置。你可以看到差异here基本上它是:

之间的区别
// Thick lines because they are scaled too
var bottom = svg.append('g').attr('transform', 'scale('+scale+','+scale+')');
bottom.selectAll('circle')
    .data(data)
    .enter().append('circle')
    .attr('cx', function(d) { return d.x; })
    .attr('cy', function(d) { return d.y; });

// line thicknesses are nice and thin
var top = svg.append('g');
top.selectAll('circle')
    .data(data)
    .enter().append('circle')
    .attr('cx', function(d) { return d.x * scale; })
    .attr('cy', function(d) { return d.y * scale; });

使用映射可能你最好的解决方案就是像你一样计算你的偏移和缩放,然后将它们添加到你的投影函数中 - 你想直接修改投影后的x和y值。如果您正确更新投影功能,则无需执行任何其他操作即可将适当的缩放应用于地图。