只能使用 snap.svg 在 svg 中拖动圆圈

Only able to drag circle in svg using snap.svg

我正在尝试使用 snap.svg。我创建了一个圆、一个矩形和一个图像。我可以拖动圆圈但不能拖动其他任何东西。我不知道出了什么问题。最近 1 小时一直在排除故障。

var s = Snap(400,400);
var img_src = "http://static.jsbin.com/images/dave.min.svg";
var rectangle = s.rect(160, 190, 150,150);
var bigCircle = s.circle(100, 100, 100);
var image = s.image(img_src, 10, 10, 80, 80);

var moveFunc = function (dx, dy, posx, posy) {      
  this.attr( { cx: posx , cy: posy } );
};

bigCircle.drag( moveFunc,
                function(){
                    console.log("Move started");
                },
                function(){
                    console.log("Move stopped");
                }
 );

rectangle.drag( moveFunc,
                function(){
                    console.log("Move started");
                },
                function(){
                    console.log("Move stopped");
                }
 );

我使用的工作代码: http://jsbin.com/vanequ/edit?html,js,output

更新: 当我不将移动功能传递给矩形和图像时,它似乎可以工作。但是,当功能处于循环状态时它会起作用。我不知道为什么。由于我对snap.svg还没有完全理解,这可能与我的无知有关。

有效:

rectangle.drag();
image.drag();

您的 moveFunc 正在设置 cx/cy 属性。圆形元素使用 cx/cy 属性定位,而矩形和图像元素使用 x/y 属性定位。因此,moveFunc 仅适用于圆形元素。一种可能的解决方案是使用两个移动函数:一个用于设置 cx/cy 的圆的函数和一个用于设置 x/y 的 rect/image 的函数。例如...

var s = Snap(400,400);
var img_src = "http://static.jsbin.com/images/dave.min.svg";
var rectangle = s.rect(160, 190, 150,150);
var bigCircle = s.circle(100, 100, 100);
var image = s.image(img_src, 10, 10, 80, 80);

var moveCircleFunc = function (dx, dy, posx, posy) {      
  this.attr( { cx: posx , cy: posy } );
};
var moveRectFunc = function (dx, dy, posx, posy) {      
  this.attr( { x: posx , y: posy } );
};

bigCircle.drag( moveCircleFunc,
                function(){
                    console.log("Move started");
                },
                function(){
                    console.log("Move stopped");
                }
 );

rectangle.drag( moveRectFunc,
                function(){
                    console.log("Move started");
                },
                function(){
                    console.log("Move stopped");
                }
 );
image.drag( moveRectFunc,
                function(){
                    console.log("Move started");
                },
                function(){
                    console.log("Move stopped");
                }
 );