我怎么能填满已经越过的svg路径?

时间:2014-05-30 12:22:54

标签: javascript jquery css svg raphael

我有一个必须沿路径移动的对象(我找到解决方案的行为),但我还必须用另一种颜色“填充”,即交叉的路径。

Here是我目前管理的一个例子。 代码看起来像这样:

var searchDl = 1;
var l = 0;

// Creates canvas 320 × 200 at 10, 50
var r = Raphael(10, 50, 520, 500);

var p = r.path("M150 10 L75 200 L225 200 L325 100").attr({stroke: "#ddf","stroke-width":5}),
    pt = p.getPointAtLength(l);
    e = r.ellipse(pt.x, pt.y, 7, 7).attr({stroke: "none", fill: "#f00"}),
    totLen = p.getTotalLength(),


start = function () {
    // storing original coordinates
    this.ox = this.attr("cx");
    this.oy = this.attr("cy");
    this.attr({opacity: 1});
},
move = function (dx, dy) {
    var tmpPt = {
        x : this.ox + dx, 
        y : this.oy + dy
    };
    // move will be called with dx and dy
    l = gradSearch(l, tmpPt);
    pt = p.getPointAtLength(l);
    this.attr({cx: pt.x, cy: pt.y});
},
up = function () {
    // restoring state
    this.attr({opacity: 1});
},
gradSearch = function (l0, pt) {
    l0 = l0 + totLen;
    var l1 = l0,
        dist0 = dist(p.getPointAtLength(l0 % totLen), pt),
        dist1,
        searchDir;

    if (dist(p.getPointAtLength((l0 - searchDl) % totLen), pt) > 
       dist(p.getPointAtLength((l0 + searchDl) % totLen), pt)) {
        searchDir = searchDl;
    } else {
        searchDir = -searchDl;
    }

    l1 += searchDir;
    dist1 = dist(p.getPointAtLength(l1 % totLen), pt);
    while (dist1 < dist0) {
        dist0 = dist1;
        l1 += searchDir;
        dist1 = dist(p.getPointAtLength(l1 % totLen), pt);
    }
    l1 -= searchDir;

    return (l1 % totLen);
},
dist = function (pt1, pt2) {
    var dx = pt1.x - pt2.x;
    var dy = pt1.y - pt2.y;
    return Math.sqrt(dx * dx + dy * dy);
};
e.drag(move, start, up);

我应该如何开始?我应该调查什么?

1 个答案:

答案 0 :(得分:2)

您是否有效地尝试从开始到当前位置创建“跟踪”?

如果是这样,你可能想要element.getSubpath(start,length);删除并添加每个移动路径。你无法真正填充现有的路径,因为你需要拆分它,但是你不能再移动它了。因此,在现有的路径上设置临时突出显示路径应该可以。

附加代码如下......

if( highlightPath ) { highlightPath.remove(); }    
pathString = p.getSubpath(0,l);

highlightPath = r.path( pathString )
                 .attr({ stroke: 'blue',  "stroke-width":5});

jsfiddle