2

我想在 SVG 中创建一条固定在一点的直线。当用户单击并拖动另一个端点时,该端点会跟随他们的光标。我正在使用snap.svg这个。

我这样做的想法是首先画一条线:

var line = paper.line( 300, 250, 450, 150 );

line.attr({
  stroke: "#000",
  strokeWidth: 5,
  strokeLinecap:"round"
});

然后创建一个我跟踪拖动事件的控制圈。在拖动回调中,我将使用传递的and参数更新行的x2andy2属性。dxdy

我注意到的第一件事是简单地设置导致事情爆炸的属性。我不完全确定我理解为什么会这样,但似乎我的回调在有机会运行之前被反复调用。然后,当它“赶上”自己时,它会以某种方式过冲。我不太确定。

无论如何,通过谷歌搜索,我能够确定在控制圈上使用 transform 属性可以让我模拟默认drag方法:

var move = function(dx,dy) {
  // This appends the new transform to the original
  this.attr({
    transform: this.data('origTransform') + (this.data('origTransform') ? "T" : "t") + [dx, dy]
  });
} 

// Maybe this saves the current transform if it hasn't happened yet?
var start = function() {
  this.data('origTransform', this.transform().local );
}

var circle = paper.circle( 450, 150, 5 );

circle.drag(move, start);

在这一点上,我被困住了。我不能对行的and属性使用相同的transform技巧。如果我直接设置它们,我会遇到过冲问题。x2y2

SVG 专业人士——对如何做到这一点有任何想法吗?

4

1 回答 1

10

我制作了示例代码。 http://jsdo.it/defghi1977/kxK1


var paper = Snap().attr({width:"500",height:"500"});
var line = paper.line(0,0,100,100)
    .attr({strokeWidth:5,stroke:"black",strokeLinecap:"round"});
var circle = paper.circle(100,100,10).attr({fill:"red"});
var x,y;
circle.drag(function(dx,dy){
    circle.attr({cx:+x+dx,cy:+y+dy});
    line.attr({x2:+x+dx,y2:+y+dy});
},function(){
    x = line.attr("x2");
    y = line.attr("y2");
},function(){});
于 2014-04-17T02:34:00.860 回答