0

如何在 raphaelJS 中进行调色板行为(将元素从“调色板”拖放到“画布”)?

4

1 回答 1

2

您必须将此 startFunction 添加到每个调色板元素:

//DragFunctions is the object that has all the 3 d&d methods, clearer in the complete file
paletteStart: function () {
    // keep the relative coords at the start of the drag
    this.ox = 0;
    this.oy = 0;

    // as we are dragging the palette element, we clone it to leave one in his place.
    var newPaletteObj = this.clone();

    //we give the new palette element the behaviour of a palette element
    DragFunctions.addDragAndDropCapabilityToPaletteOption(newPaletteObj);

    //nice animation
    this.animate({
        "opacity": 0.5
    }, 500);
}

现在我们需要在拖动元素时使用该函数:

move: function (dx, dy) {
    // calculate translation coords
    var new_x = dx - this.ox;
    var new_y = dy - this.oy;

    // transforming coordinates
    this.transform('...T' + new_x + ',' + new_y);

    // save the new values for future drags
    this.ox = dx;
    this.oy = dy;
}

最后,在完成删除时执行的函数:

paletteUp: function () {
    if (!DragFunctions.isInsideCanvas(this)) {
        this.remove();
        //notify the user as you want!
    } else {
        //Giving the new D&D behaviour
        this.undrag();
        //give the element the new d&d functionality!
        this.animate({
            "opacity": 1
        }, 500);
    }
}

这里有两件事要评论,当元素被删除时,你将不得不删除调色板行为并给它另一个(一个普通的 d&d 功能),如果没有,它将继续克隆周围的元素。在这里,我给你一些很好的行为来给他们:

start: function () {
    // keep the relative coords at the start of the drag
    this.ox = 0;
    this.oy = 0;
    // animate attributes to a "being dragged" state
    this.animate({
        "opacity": 0.5
    }, 500);
},
//same move function
up: function () {
    if (!DragFunctions.isInsideCanvas(this)) {
        this.animate({
            transform: '...T' + (-this.ox) + ',' + (-this.oy)
        }, 1000, "bounce");
    }
    this.animate({
        "opacity": 1
    }, 500);
},

//and the method that gives the behaviour
addDragAndDropCapabilityToSet: function (compSet) {
    compSet.drag(this.move, this.start, this.up, compSet, compSet, compSet);
}

您可能还看到,我们有一个验证器来查看元素是否在画布内,这是一个非常有用的功能,这里:

isInsideCanvas: function (obj) {
    var canvasBBox = //get your 'canvas'
    var objectBBox = obj.getBBox();
    var objectPartiallyOutside = !Raphael.isPointInsideBBox(canvasBBox, objectBBox.x, objectBBox.y) || !Raphael.isPointInsideBBox(canvasBBox, objectBBox.x, objectBBox.y2) || !Raphael.isPointInsideBBox(canvasBBox, objectBBox.x2, objectBBox.y) || !Raphael.isPointInsideBBox(canvasBBox, objectBBox.x2, objectBBox.y2);
    return !(objectPartiallyOutside);
} Finally,
the place to call to give the element all this behaviour:

//this works for elements and sets
addDragAndDropCapabilityToPaletteOption: function (compSet) {
    compSet.drag(this.move, this.paletteStart, this.paletteUp, compSet, compSet, compSet);
}

我创建的一个与 raphael 一起玩的网站上有一个演示,名为 comoformamos.com。漏洞代码位于 github gist 或托管在 github 上,因此,如果您想更深入地了解代码,请随意进行。

在这个博客条目中解释得更漂亮:devhike,我是作者。

于 2012-11-04T17:07:30.100 回答