2014-12-04 63 views
0

我是新的拉斐爾JS和我測試一些關於它。 我必須創建一個路徑並將其拖動。拉斐爾JS拖動路徑,並在紙上保持它

目前沒有問題。

我真正的問題是我必須限制進入紙張的行動。 我的路徑必須是約束移動到我的raphael紙。

(function() { 
    var trans_x; 
    var trans_y; 
    var w = 300; 
    var h = 300; 

    var paper = Raphael('holder', w, h); 
    var rectPath = paper.path("M0, 0L0, 90L90, 90L90, 0Z"); 
    rectPath.attr({ 
    fill: "green", 
    cursor: "move" 
    }); 

    var bBox = rectPath.getBBox(); 

    var startPath = function() { 
     this.ox = this.attr("x"); 
     this.oy = this.attr("y"); 
    }, 
    movePath = function(dx, dy) { 

     trans_x = dx - this.ox; 
     trans_y = dy - this.oy; 

     this.translate(trans_x, trans_y); 

     this.ox = dx; 
     this.oy = dy; 

    }, 
    upPath = function() {}; 


    rectPath.drag(movePath, startPath, upPath); 

})(); 

這是我基本的代碼在小提琴:

http://jsfiddle.net/Drzep/7s8rxhat/4/

我tryed很多事情與math.min和math.max但沒有任何工程的路徑。 我發現如何用raphael circle和rect來做到這一點,但沒有找到路徑。

+0

可以使用setviewBox屬性。 – Ved 2014-12-05 05:37:19

+0

如果你已經可以用圓或矩形做這個,你應該可以在路徑等任何元素上使用getBBox()方法來獲取它的x1,x2,y1,y2點來進行比較。只需運行getBBox()並查看輸出。 – Ian 2014-12-05 08:23:09

+0

感謝您的評論,我之前嘗試過使用getBbox,但發現不一致的結果(我認爲)。你能告訴我,Bbox的x和y結果在這裏是否正常? (Console.log)http://jsfiddle.net/Drzep/7s8rxhat/5/ – cmuller 2014-12-05 10:22:56

回答

0

我只是改寫了你的代碼稍微簡單一些,

我覺得你變了BBOX搞亂,所以我刪除了:

var nowX; 
var nowY; 
var paper = Raphael(0,0,300,300); 
var rect = paper.rect(100, 100, 30, 30).attr({ fill: "blue", cursor: "move" }); 
var rectPath = paper.path("M0, 0L0, 90L90, 90L90, 0Z").attr({ fill: "green", cursor: "move", stroke: "#fff" }); 
function start() { 
    this.ox = this.getBBox().x; 
    this.oy = this.getBBox().y; 
}; 
function move(dx, dy) { 
    nowX = Math.min((paper.width - this.getBBox().width), this.ox + dx); 
    nowY = Math.min((paper.height - this.getBBox().height), this.oy + dy); 
    nowX = Math.max(0, nowX); 
    nowY = Math.max(0, nowY); 
    if (this.type == "rect") { 
    this.attr({ x: nowX, y: nowY }); 
    } 
    else { 
    this.transform("T" + nowX + "," + nowY); 
    } 
}; 
function up() { 
}; 
rect.drag(move, start, up); 
rectPath.drag(move, start, up); 

http://jsfiddle.net/crockz/ttfy22fq/

+0

謝謝Crockz。這是很好的。現在非常清楚。我明白爲什麼以前不行。我想我正在尋找一個使用Bbox太複雜的解決方案。非常感謝。 – cmuller 2014-12-08 15:45:22