2014-02-06 122 views
0

我雙擊一個畫布創建一個元素,用戶可以這樣做n次。每個元素都是可拖動的。獲取相對於畫布拖動後的畫布元素的位置

對於每個元素,如果將其拖動到x/y座標的某個矩形內,那麼我想在該矩形內部clearRect(),從而有效地刪除拖動的元素。

這是怎麼實現的?

電流:

var stage = new Kinetic.Stage({ 
    container: 'container', 
    width: 662, 
    height: 983 
}); 
var layer = new Kinetic.Layer(); 
stage.add(layer); 

$(stage.getContent()).on('dblclick', function (event) { 
    var pos = stage.getMousePosition(); 
    var mouseX = parseInt(pos.x); 
    var mouseY = parseInt(pos.y); 
    var text = new Kinetic.Text({ 
     x: mouseX, 
     y: mouseY, 
     text: cc, 
     fill: "blue", 
     draggable: true, 
    }); 
    layer.add(text); 
    layer.draw(); 
} 
+0

我不認爲'getMousePosition()'是一個工作功能 – JLewkovich

回答

0

可以使用yourElement.on( 「dragend」,處理程序)來測試的元素是刪除矩形內。

如果它在裏面,您可以使用yourElement.destroy()來銷燬該元素。

示例代碼和演示:http://jsfiddle.net/m1erickson/jqPhe/

var stage = new Kinetic.Stage({ 
    container: 'container', 
    width: 350, 
    height: 350 
}); 
var layer = new Kinetic.Layer(); 
stage.add(layer); 


// define the boundaries of the deletion box 

var dx=200; 
var dy=40; 
var dw=100; 
var dh=100; 


// create the deletion box 

var deleteMe=new Kinetic.Rect({ 
    x:dx, 
    y:dy, 
    width:dw, 
    height:dh, 
    stroke:"red" 
}); 
layer.add(deleteMe); 
var label=new Kinetic.Text({ 
    x:dx, 
    y:10, 
    text:"Drag here to delete\n(Must be fully inside)", 
    fill:"black" 
}); 
layer.add(label); 


// create a circle element for testing purposes 

var circle1 = new Kinetic.Circle({ 
    x:100, 
    y:100, 
    radius: 30, 
    fill: 'red', 
    stroke: 'black', 
    strokeWidth: 4, 
    draggable: true 
}); 

// on dragend: test if this circle is inside the deletion rectangle. If yes, delete this circle. 

circle1.on("dragend",function(){ 
    var x=this.getX(); 
    var y=this.getY(); 
    if(x>=dx && x<=dx+dw && y>=dy && y<=dy+dh){ 
     this.destroy(); 
     layer.draw(); 
    } 
}); 
layer.add(circle1); 
layer.draw();