Bounding snap.svg element to svg area

不羁的心 提交于 2019-12-12 09:27:13

问题


I am new to snap.svg and I have been able to make my circle and make it draggable but I can drag it out of the area I gave my svg and then it is lost on the page. How can I bound it so that it can not go out of the area I gave for my svg?

Here is my basic code:

<body>
<svg id="svg" style="width:700px; height:600px;"></svg>
</body>
<script>
var s = Snap('#svg')
var circle = s.circle(150, 150, 100)
circle.drag();
</script>

Thanks for your help!


回答1:


Just in case someone stumbles upon this one, I had a play with something a while back that may help...its a bit overkill, but it can be simplified further if you don't need to be bothered about things like a viewBox on the svg. So thought I would include the full lot in case it helps.

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

    Element.prototype.limitDrag = function( params ) {
        this.data('minx', params.minx ); this.data('miny', params.miny );
        this.data('maxx', params.maxx ); this.data('maxy', params.maxy );
        this.data('x', params.x );    this.data('y', params.y );
        this.data('ibb', this.getBBox() );
        this.data('ot', this.transform().local );
        this.drag( limitMoveDrag, limitStartDrag );
        return this;    
    };

    function limitMoveDrag( dx, dy ) {
        var tdx, tdy;
        var sInvMatrix = this.transform().globalMatrix.invert();
            sInvMatrix.e = sInvMatrix.f = 0; 
            tdx = sInvMatrix.x( dx,dy ); tdy = sInvMatrix.y( dx,dy );

        this.data('x', +this.data('ox') + tdx);
        this.data('y', +this.data('oy') + tdy);
        if( this.data('x') > this.data('maxx') - this.data('ibb').width  ) 
            { this.data('x', this.data('maxx') - this.data('ibb').width  ) };
        if( this.data('y') > this.data('maxy') - this.data('ibb').height ) 
            { this.data('y', this.data('maxy') - this.data('ibb').height ) };
        if( this.data('x') < this.data('minx') ) { this.data('x', this.data('minx')     ) };
        if( this.data('y') < this.data('miny') ) { this.data('y', this.data('miny') ) };
        this.transform( this.data('ot') + "t" + [ this.data('x'), this.data('y') ]  );
    };

    function limitStartDrag( x, y, ev ) {
        this.data('ox', this.data('x')); this.data('oy', this.data('y'));
    };
  })

// example use
var myCircle2 = s.circle(20,20,20)
             .attr({ fill: 'blue' })
             .limitDrag({ x: 0, y: 0, minx: 0, miny: 0, maxx: 100, maxy: 100 });

Test example



来源:https://stackoverflow.com/questions/25050058/bounding-snap-svg-element-to-svg-area

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!