JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<h1>Rotation</h1>
<div id="graph1"></div>
<div id="marker">Wherever you click, it rotates to here</div>
</body>
CSS
#graph1 {
position:absolute;
top:100px;
left:50px;
width:400px;
height:400px;
background-image:url('http://www.showmethemath.com/Math_Practice/coordinateGridSquareScaleOf2.gif');
background-position:center center;
background-size:contain;
background-repeat:no-repeat;
transition:transform 1s ease;
transform:rotate(30deg);
transform-origin:50% 50%;
border-radius:50%;
}
#marker {
position: absolute;
top:300px;
left:450px;
border-top:1px solid black;
}
JavaScript
$(function () {
// calculate graph center
var graph = {
centerY: (parseInt($('#graph1').css("top"), 10) + $('#graph1').height() / 2),
centerX: (parseInt($('#graph1').css("left"), 10) + $('#graph1').width() / 2)
};
// this tracks the degrees, which is always positive
// only have to get the current rotation to start
var totalDegrees = getCSSRotation("#graph1");
$('body').on('click', '#graph1', function (e) {
console.log('********************');
// get radians from clickpoint; convert to degrees
var clickRadiansFromZero = Math.atan2(e.clientY - graph.centerY, e.clientX - graph.centerX);
var offsetDegrees = degrees(clickRadiansFromZero);
if (offsetDegrees <= 0) {
offsetDegrees = Math.abs(offsetDegrees);
} else {
offsetDegrees = 360 - offsetDegrees;
}
totalDegrees += offsetDegrees;
console.log("Offset: " + offsetDegrees);
$('#graph1').css('transform', 'rotate(' + (totalDegrees) + 'deg)');
});
});
function degrees(radians) {
return radians * 180 / Math.PI;
};
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;
}