我有一個圓形項目,點擊後會旋轉到預定義的位置。它幾乎在那裏,但最後一個要求是它總是順時針旋轉到標記。我似乎無法弄清楚如何獲得正確的值,以便當我設置CSS變換:旋轉(Xdeg)時,它將始終順時針旋轉。保持0到360之間的角度對另一部分也是好的,但不是必要的。旋轉元素以點擊位置
看到這個小提琴,下面的JavaScript以及Rotation
$(function() {
$('body').on('click', '#graph1', function (e) {
console.log('********************');
//get mouse position relative to div and center of div for polar origin
var pos = getMousePosAndCenter(e, 'graph1');
//get the current degrees of rotation from the css
var currentRotationDegrees = getCSSRotation('#graph1');
console.log('CSS Rotation Value: ' + currentRotationDegrees);
//current rotation in radians
var currentRotationRadians = radians(currentRotationDegrees);
//radians where clicked
var clickRadiansFromZero = Math.atan2(pos.y - pos.originY, pos.x - pos.originX);
//degrees the click is offset from 0 origin
var offsetDegrees = degrees(clickRadiansFromZero);
//how many degrees to rotate in css to put the mouse click at 0
var degreesToZero;
if (offsetDegrees >= 0)
degreesToZero = currentRotationDegrees - Math.abs(offsetDegrees);
else
degreesToZero = currentRotationDegrees + Math.abs(offsetDegrees);
console.log("Degrees to Zero: " + degreesToZero);
//distance in pixels from origin
var distance = calculateDistance(pos.originX, pos.originY, pos.x, pos.y);
console.log("Distance From Origin(px): " + distance);
$('#graph1').css('transform','rotate(' + degreesToZero + 'deg)')
});
});
function getMousePosAndCenter(e, id) {
var rect = document.getElementById(id).getBoundingClientRect();
return {
x: (((e.clientX - rect.left)/rect.width) * rect.width) + 0.5 << 0,
y: (((e.clientY - rect.top)/rect.height) * rect.height) + 0.5 << 0,
originY: (rect.height/2),
originX: (rect.width/2)
};
}
function radians(degrees) {
return degrees * Math.PI/180;
};
function degrees(radians) {
return radians * 180/Math.PI;
};
function calculateDistance(originX, originY, mouseX, mouseY) {
return Math.floor(Math.sqrt(Math.pow(mouseX - originX, 2) + Math.pow(mouseY - originY, 2)));
}
function getCSSRotation(id) {
var matrix = $(id).css('transform');
var values = matrix.split('(')[1],
values = values.split(')')[0],
values = values.split(',');
var a = values[0];
var b = values[1];
var c = values[2];
var d = values[3];
var cssRotation = degrees(Math.atan2(b, a));
return cssRotation;
}
加入了小提琴我的答案,給出你的CSS流體幀率。 – jookyone