http://jsfiddle.net/wRexz/4/
var dragging = false, startpoint, endpoint, midpoint = $("#center").position();
midpoint = {x:midpoint.left - 2, y:midpoint.top-2};
$("#stage").mousedown(function(e){
dragging = true;
startpoint = {x:e.offsetX, y:e.offsetY};
});
$("#stage").mouseup(function(e){
dragging = false;
});
$("#stage").mousemove(function(e){
if (dragging){
var angle = 0, sp = startpoint, mp = midpoint;
var p = {x:e.offsetX, y:e.offsetY};
var sAngle = Math.atan2((sp.y-mp.y),(sp.x - mp.x));
var pAngle = Math.atan2((p.y-mp.y),(p.x - mp.x));
angle = (pAngle - sAngle) * 180/Math.PI;
$("#display").text(angle);
$('#rotateme').css({ rotate: '+=' + angle });
startpoint = {x:p.x, y:p.y};
}
});
这将找到两点之间的相对旋转角度。每次mousemove
触发事件时它都会更新,因此它一次不会超过 180 度(除非在中点拖动时)。Math.atan2
与后者相比,简化了逻辑,Math.atan
因为后者不适用于坐标系。