ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

javascript – raphaeljs如何使用约束运动限制元素拖动(在父边界框内)

2019-08-26 05:39:41  阅读:283  来源: 互联网

标签:bounding-box drag javascript constraints raphael


我试图调整此示例http://raphaeljs.com/graffle.html以限制拖动到容器svg内.

有点像http://bl.ocks.org/1557377http://jqueryui.com/demos/draggable/#constrain-movement基本上我想限制拖动时从边界框移出的对象.

这是添加到移动功能的调整代码(http://jsfiddle.net/f4mFQ/1/)

    if(thisBox.x < 0){
        ddx = 0;
    }else if(thisBox.x>width-thisBox.width ){
        ddx = width-thisBox.width;
    }else {
        ddx = this.ox + dx;
    }

    if(thisBox.y < 0){
        ddy = 0;
    }else if(thisBox.y>height-thisBox.height ){
        ddy = height-thisBox.height;
    }else{
        ddy = this.oy + dy;
    }

这部分有效,当矩形移动超出边界时,它会在边缘上跳舞!而圆和椭圆卡在边缘.

因此,在这种情况下,如何在父边界框内使用约束移动限制元素拖动svg

解决方法:

一个问题是,当您将ddx或ddy设置为位于一侧时,您将该值作为椭圆的中心点返回,以便它们“捕捉”到侧面.

第二件事是你在这个边界框的左上角进行计算,而不是这个(ox dx)的实际计算位置.这就是造成混乱的原因.

这不是最漂亮的实现,但我想最小化对代码的更改,用这个替换move函数:

 move = function (dx, dy) {
    var width =this.paper.width,
    height = this.paper.height,
    thisBox = this.getBBox()
    //, box = {
    //     "x"      :thisBox.width,
    //     "y"      :thisBox.height,
    //     "x2"     :width-thisBox.width,
    //     "y2"     :height-thisBox.height,
    //     "width"  :width-thisBox.width,
    //     "height" :height-thisBox.height
    // };
    // var outOfBound=!Raphael.isBBoxIntersect(thisBox,box)
    ;

    console.log(thisBox.width,width,thisBox.x,thisBox
                ,this.ox);

    var ddx = this.ox + dx;
    var ddy = this.oy + dy;
    if (this.type == 'ellipse') { 
        ddx -= thisBox.width / 2;
        ddy -= thisBox.height / 2;
    }

    if(ddx < 0){
        ddx = 0;
    }else if(ddx>width-thisBox.width ){
        ddx = width-thisBox.width;
    }

    if(ddy < 0){
        ddy = 0;
    }else if(ddy>height-thisBox.height ){
        ddy = height-thisBox.height;
    }

    var att = this.type == "rect" ? {x: ddx, y: ddy} : {cx: ddx + (thisBox.width / 2), cy: ddy + (thisBox.height / 2)};
    this.attr(att);


    for (var i = connections.length; i--;) {
        r.connection(connections[i]);
    }
    r.safari();
} 

在开始时,我们根据此位置计算ddx和ddy作为左上角. (如果它是椭圆,则调整,因为ox和oy是中心坐标).

然后它与之前的情况大致相同,但是当我们将值设置回来时,我们会重新调整椭圆的值.您可以更改存储/使用的值以避免重复计算.

这对我行得通.

编辑

将代码复制到自己的fiddle中.

标签:bounding-box,drag,javascript,constraints,raphael
来源: https://codeday.me/bug/20190826/1726587.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有