【问题标题】:How to create a set of two elements: Raphael如何创建一组两个元素:Raphael
【发布时间】:2015-09-26 05:43:47
【问题描述】:

我的画布上有两个矩形,现在如果我将其中一个拖到另一个上面,我希望它们对齐。我想我需要使用 set() 但不确定如何使用。这是我到目前为止所得到的。

$(document).ready(function(){
    var paper = Raphael(20, 20, 5000, 5000);

var rect1 = paper.rect(50, 50, 50, 50).attr({
    fill: "hsb(.8, 1, 1)",
    stroke: "none",
    opacity: .5,
});

var rect2 = paper.rect(50, 50, 50, 50).attr({
    fill: "hsb(.8, 1, 1)",
    stroke: "none",
    opacity: .5,
});

var rectStart = function() {
        this.ox = this.attr("x");
        this.oy = this.attr("y");
        this.attr({opacity: 1});
    },
    rectMove = function(dx, dy) {
        this.attr({x: this.ox + dx, y: this.oy + dy});
    },
    rectUp = function(){
        this.attr({opacity: .5});
    };


rect1.drag(rectMove, rectStart, rectUp);
rect2.drag(rectMove, rectStart, rectUp);

【问题讨论】:

    标签: javascript raphael


    【解决方案1】:

    您只需在rectUp 方法中编写逻辑即可。

    这是工作的fiddle

    var paper = Raphael(20, 20, 5000, 5000);
    
    var rect1 = paper.rect(50, 50, 50, 50).attr({
        fill: "hsb(.8, 1, 1)",
        stroke: "none"
    });
    rect1.track_x = 50;
    rect1.track_y = 50;
    
    var rect2 = paper.rect(150, 50, 50, 50).attr({
        fill: "#aa9988",
        stroke: "none"
    });
    rect2.track_x = 150;
    rect2.track_y = 50;
    
    function rectStart() {
    }
    
    function rectMove(dx, dy) {
        this.attr({x: this.track_x + dx, y: this.track_y + dy});
    }
    
    function rectUp() {
    
        this.track_x = this.attr("x");
        this.track_y = this.attr("y");
        var currentDragRect, idleRect;
        if(this == rect1) {
            currentDragRect = rect1;
            idleRect = rect2;
        } else {
            currentDragRect = rect2;
            idleRect = rect1;
        }
        /*
        r11   r12     currentDragRect
        r21   r22     idleRect
        */
        //r11 <= r22 && r21 <= r12
        //50 is width and height
        if( (currentDragRect.track_x <= (idleRect.track_x + 50)) &&
            (idleRect.track_x <= (currentDragRect.track_x + 50)) ) {
    
            if( (currentDragRect.track_y <= (idleRect.track_y + 50)) &&
                (idleRect.track_y <= (currentDragRect.track_y + 50)) ) {
    
                //p.translate(300, 100);
                alert('Done  ' + idleRect.track_x);
                currentDragRect.attr({x: idleRect.track_x, y: idleRect.track_y});
                //currentDragRect.transform('t' + idleRect.track_x + ','+ idleRect.track_y);
    
            }
    
        }
    }
    
    rect1.drag(rectMove, rectStart, rectUp);
    rect2.drag(rectMove, rectStart, rectUp);
    

    我也尝试过使用Element.onDragOver,但正如预期的那样使用didnt work。所以正如SO answer 中所说,跟踪坐标将有助于解决此类问题。

    【讨论】:

      猜你喜欢
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      • 2015-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多