2013-02-25 17 views

回答

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/

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 
})