JSFiddle - React, Tailwind, and code Playground
HTML
<div class="wrapper">
<div id="rotate" class="rotate-square">
<div class="corner" />
</div>
</div>
CSS
.wrapper {
height: 300px;
width: 400px;
background: red;
display: flex;
justify-content: center;
align-items: center;
}
.rotate-square {
background: blue;
height: 150px;
width: 150px;
}
.corner {
height: 30px;
width: 30px;
background: green;
}
JavaScript
const rotate = document.getElementById('rotate');
var mouseDown = false;
rotate.addEventListener('mousedown', (e) => {
mouseDown = true;
});
rotate.addEventListener('mousemove', (e) => {
const elem = e.target;
if (mouseDown) {
const boundingRect = elem.getBoundingClientRect();
const center_x = boundingRect.left + boundingRect.width / 2;
const center_y = boundingRect.top + boundingRect.height / 2;
const mouse_x = e.pageX;
const mouse_y = e.pageY;
const radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
const degree = radians * (180 / Math.PI) * -1 + 90;
rotate.style.transform = `rotate(${degree}deg)`;
}
});
rotate.addEventListener('mouseup', (e) => {
mouseDown = false;
});