7

我正在使用 D3.js 从 GeoJSON 文件生成和呈现路径。这很好用,但现在我想沿着这条路径为对象设置动画。我知道如何使用 D3 和标准 SVG 做到这一点:

  1. 创建过渡并设置其持续时间
  2. 对于过渡的每一帧,使用 % complete 来查找沿路径的坐标
  3. 将对象移动到步骤 2 中找到的坐标

这很简单。但是我遇到的问题是 d3.geo.path() 似乎没有像标准 D3 路径对象那样返回任何长度或位置数据(例如有用的 getPointAtLength() 方法)。所以我无法找到沿路径 25% 的点的 x,y 坐标。

有没有办法获取这些数据?(或者有没有更好的方法,比如将 d3.geo.path() 转换为常规的 D3 路径?)

以下是我的代码的截断版本;一个活生生的例子在这里:http: //jsfiddle.net/5m35J/4/

json = {
    ... // snipped for brevity
};

// Draw a GeoJSON line on the map:

map = $('#map');
xy = d3.geo.mercator().scale(480000).translate([630700, 401100]);
path = d3.geo.path().projection(xy);

vis = d3.select("#map")
    .append("svg:svg")
    .attr("width", 960)
    .attr("height", 600);

vis.append("svg:g")
    .attr("class", "route")
    .selectAll("path")
    .data(json.features)
    .enter()
    .append("svg:path")
    .attr("d", path)
    .attr("fill-opacity", 0.5)
    .attr("fill", "#fff")
    .attr("stroke", "#333");

// Draw a red circle on the map:

//len = 100; // how do I find the length of the path?
origin_x = 100;
origin_y = 100;

group = vis.append("svg:g");

circle = group.append("circle")
    .attr({
    r: 10,
    fill: '#f33',
    transform: function () {
        //var p = path.getPointAtLength(0)
        //return "translate(" + [p.x, p.y] + ")";
        return "translate("+ origin_x +","+ origin_y +")";
    }
});

// Animate the circle:

duration = 5000;
circle.transition()
    .duration(duration)
    .ease("linear")
    .attrTween("transform", function (d, i) {
    return function (t) {
        //var p = path.node().getPointAtLength(len*t) // d3.geo.path() doesn't provide a getPointAtLength() method!
        //return "translate("+[p.x,p.y]+")"
        var current_x = origin_x + origin_x * t;
        var current_y = origin_y + origin_y * t;            
        return "translate("+ current_x +","+ current_y +")";
    }
});
4

1 回答 1

10

好吧,我想通了,但我不完全确定我的解决方案是否是“正确”的方法。基本上,我使用 D3 选择由 d3.geo.path() 对象创建的原始 SVG 元素。

请注意对targetPathpathNodepathLength变量以及对transform()attrTween()函数的更改:

// Draw a red circle on the map:

group = vis.append("svg:g");

var targetPath = d3.selectAll('.route')[0][0],
    pathNode = d3.select(targetPath).selectAll('path').node(),
    pathLength = pathNode.getTotalLength();

circle = group.append("circle")
    .attr({
    r: 10,
    fill: '#f33',
    transform: function () {
        var p = pathNode.getPointAtLength(0)
        return "translate(" + [p.x, p.y] + ")";
    }
});

// Animate the circle:

duration = 10000;
circle.transition()
    .duration(duration)
    .ease("linear")
    .attrTween("transform", function (d, i) {
    return function (t) {
        var p = pathNode.getPointAtLength(pathLength*t);
        return "translate(" + [p.x, p.y] + ")";
    }
});

现场示例在这里:http: //jsfiddle.net/5m35J/6/

于 2013-07-22T18:52:25.327 回答