获取拖动形成的线的长度

时间:2013-02-25 05:46:37

标签: javascript html5 kineticjs

我想计算阻力的长度。即通过在html画布上将光标从一个点拖动到另一个点而创建的行的长度。如何在kineticjs中实现它? 即在dragstart到dragend。

2 个答案:

答案 0 :(得分:1)

我不知道动能,但使用jquery看起来像这样:

var telemetry = {
    $target: null,
    startPosition: {x:0,y:0},
    distance: 0,
    getMousePosition: function(event){
        var position = {
            x: event.pageX - this.$target.offset().left,
            y: event.pageY - this.$target.offset().top
        }
        return position;
    },
    getDistance: function(startPosition, endPosition){
        //find distance in each x and y directions
        var dx = endPosition.x - startPosition.x;
        var dy = endPosition.y - startPosition.y;

        // use pythagorean theorem
        return Math.sqrt((dx*dx) + (dy*dy));
    },
    onMouseDown: function(event){
        this.startPosition = this.getMousePosition(event);
    },
    onMouseUp: function(event){
        this.distance = this.getDistance(this.startPosition, this.getMousePosition(event));
    }
}

telemetry.$target = $('#myCanvas');

telemetry.$target.mousedown(function(event){
    telemetry.onMouseDown(event);
}).mouseup(function(event){
    telemetry.onMouseUp(event);
    alert('you dragged ' + telemetry.distance + 'px');
});

http://jsfiddle.net/gunderson/HUdUH/

答案 1 :(得分:0)

好吧,在kineticjs你会做类似的事情:

var point1;
var point2;
layer.on('dragstart', function(){
     point1 = stage.getUserPosition();
});
layer.on('dragend', function(){
     point2 = stage.getUserPosition();
     var xDist = point2.x - point1.x;
     var yDist = point2.y - point1.y;
     alert( Math.sqrt((xDist*xDist) + (yDist*yDist)) ); // this pops up a message of the length of the line, you could just do a return or assign a value to something
     //distance = Math.sqrt((xDist*xDist) + (yDist*yDist)); //alternative
})