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

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

本文关键字:一个 位置 保存 svg 一条 一条路 拖动 路径 Snap      更新时间:2023-09-26

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

我修改了我在这里找到的这个代码。

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的新手,我尝试了一些教程来学习,但这些东西超出了我的能力范围,我真的很感激你的一些见解

编辑:这与我的代码更好,谢谢你指出伊恩。

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

因此,在我们做任何事情之前,让所有人都"锁定"原始位置"作为我们的基础。并将"sx"称为"起始位置",我们计算出每次拖动的起始位置。我们需要这个来添加"dx"(在拖动中添加的delta差)。

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

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