Snap.svg 沿路径拖动一组并保存位置

Snap.svg drag a group along a path and save position

我正在尝试使用 Snap 来操作 SVG,但在沿路径拖动一组元素时遇到了一些问题。

我修改了这个code that I found here

start = function () {
    this.data("ox", +this.getBBox().cx);
    this.data("oy", +this.getBBox().cy);
},
move = function (dx, dy) {
    var tmpPt = {
        x: this.data('ox') + dx,
        y: this.data('oy') + dy
    };
    // move will be called with dx and dy
    l = gradSearch(l, tmpPt);
    pt = path.getPointAtLength(l);

    if (!isNaN(pt.x) && !isNaN(pt.y)) {
        this.transform('t' + (pt.x - this.data("ox")) + ',' + (pt.y - this.data("oy")));
    };
},
end = function () {
    console.log('End of drag');
}

我可以拖动这个组,它会停留在我放下它的地方,但是当我再次开始拖动时,这个组会回到它的原点,如果我疯了,它就会开始出现问题。

我是 SVG 的新手,我尝试了一些教程来学习,但这些东西似乎超出了我的能力范围,我非常感谢你的一些见解

编辑:我的 code 更好,感谢 Ian 指出这一点。

我认为问题在于您每次都在重置 ox。在前面的示例中,他们使用的是 attr('cx') 而不是 ox,因此他们始终引用要偏移的形状的原始位置。当您每次都重置它时,差异将始终为零,因此它会重置为从头开始。所以你需要一些修改。

所以让所有'ox'在我们做任何事情之前'original position'作为我们的基础。 并调用 'sx' 我们找出每个拖动开始的 'starting position' 。我们将需要它来添加 'dx'(在拖动中添加的差值)。

我们可以先存储原始位置...然后更改变换以参考原始位置,而不是起始位置。

group.drag(move, start, end);
group.data("ox", +group.getBBox().cx);
group.data("oy", +group.getBBox().cy);

start = function () {
    this.data("sx", +this.getBBox().cx);
    this.data("sy", +this.getBBox().cy);
},

move = function (dx, dy) {

    var tmpPt = {
        x: this.data('sx') + dx,
        y: this.data('sy') + dy
    };

    l = gradSearch(l, tmpPt);

    pt = path.getPointAtLength(l);

    // We change this!!!
    if (!isNaN(pt.x) && !isNaN(pt.y)) {
       this.transform('t' + (pt.x - this.data("ox")) + ',' + (pt.y - this.data("oy")) );
};
},

jsfiddle