SnapSVG拖动旋转的矩形

时间:2014-12-05 23:50:54

标签: svg raphael snap.svg

我设法使用以下代码(由小方块演示)成功拖动矩形,并考虑鼠标位置

当旋转矩形时,矩形与形状平行拖动,请有人告诉我如何纠正这个问题。我认为这可以通过一些三角函数来完成但是没有成功计算出相反的(x)和相邻的(y)

可以在此处看到演示http://jsbin.com/tihobu/2/edit?html,js,output

var s = Snap(400,400);
var smallSquare = s.rect(100, 100, 50,50).attr({fill:"#ffcc00"});
var bigSquare = s.rect(100,20,150,150).attr({fill:"#ff6600"}); 
var startx, starty; 

var t = bigSquare.transform().localMatrix;
    t.rotate(45);
bigSquare.transform(t);

var moveFunc = function (dx, dy, posx, posy) {
   var xadj = startx - (0 - dx);
   var yadj = starty - (0 - dy);
   this.attr('x',xadj);
   this.attr('y',yadj);
};

var startFunc = function(){
                startx = this.attr('x');
                starty = this.attr('y');
                console.log("Move started");
            };
var stopFunc = function(){};

bigSquare.drag( moveFunc,startFunc,stopFunc );
smallSquare.drag( moveFunc,startFunc,stopFunc );

感谢大卫

1 个答案:

答案 0 :(得分:1)

问题是坐标空间已旋转,因此您有几个选项。要么计算出新的x,y的位置,要么使用带有变换的拖动而不是改变x,y。我个人会使用变换,但是你可能有很好的理由想要改变x,y属性。

请注意,如果您继续使用更改x,y属性,则会添加并非所有元素都具有此问题的问题。例如,圆圈用cx,cy定位,你可能有其他复杂的元素。

以下是我用来制作转换处理程序的一些代码...(编辑:更改了代码以应对复杂的组)

example

   Snap.plugin( function( Snap, Element, Paper, global ) {

    Element.prototype.globalToLocal = function( globalPoint ) {
            var globalToLocal = this.node.getTransformToElement( this.paper.node ).inverse();
            globalToLocal.e = globalToLocal.f = 0;
            return globalPoint.matrixTransform( globalToLocal );
    };

    Element.prototype.getCursorPoint = function( x, y ) {
            var pt = this.paper.node.createSVGPoint();      
            pt.x = x; pt.y = y;
            return pt.matrixTransform( this.paper.node.getScreenCTM().inverse()); 
    }

    Element.prototype.altDrag = function() {
            return this.drag( altMoveDrag, altStartDrag );
    };

    function altMoveDrag( xxdx, xxdy, ax, ay ) {
            var tdx, tdy;
            var cursorPoint = this.getCursorPoint( ax, ay );
            var pt = this.paper.node.createSVGPoint();

            pt.x = cursorPoint.x - this.data('op').x;
            pt.y = cursorPoint.y - this.data('op').y;

            var localPt = this.globalToLocal( pt );

            this.transform( this.data('ot').toTransformString() + "t" + [  localPt.x, localPt.y ] );

    };

    function altStartDrag( x, y, ev ) {
            this.data('ibb', this.getBBox());
            this.data('op', this.getCursorPoint( x, y ));
            this.data('ot', this.transform().localMatrix);
    };

});

相关问题