相对于画布拖动后获取canvas元素的位置

时间:2014-02-06 16:46:12

标签: javascript jquery html5 kineticjs

我双击画布来创建一个元素,用户可以这样做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();
}

1 个答案:

答案 0 :(得分:0)

您可以使用yourElement.on(“dragend”,handler)来测试元素是否在删除矩形内。

如果它在里面,你可以使用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();