console
const draggableElement = document.getElementById('draggable');
const rotateHandle = draggableElement.querySelector('.rotate-handle');
let initialAngle = 0;
let initialX, initialY;
function dragStart(event) {
initialX = event.clientX;
initialY = event.clientY;
document.addEventListener('mousemove', dragMove);
document.addEventListener('mouseup', dragEnd);
}
function dragMove(event) {
const deltaX = event.clientX;
const deltaY = event.clientY;
const newX = deltaX;
const newY = deltaY;
draggableElement.style.left = `${newX}px`;
draggableElement.style.top = `${newY}px`;
}
function dragEnd() {
document.removeEventListener('mousemove', dragMove);
document.removeEventListener('mouseup', dragEnd);
}
draggableElement.addEventListener('mousedown', dragStart);
let initialRotationAngle;
function rotateStart(event) {
event.stopPropagation();
initialAngle = getRotationAngle(event.clientX, event.clientY);
console.log(initialRotationAngle)
initialRotationAngle = initialRotationAngle === 'none' ? 0 : getRotationAngle11();
document.addEventListener('mousemove', rotateMove);
document.addEventListener('mouseup', rotateEnd);
}
function getRotationAngle11() {
const transform = getComputedStyle(draggableElement).getPropertyValue('transform');
if (transform && transform !== 'none') {
const matrix = transform.split('(')[1].split(')')[0].split(',');
console.log('1',matrix)
const angle = Math.round(Math.atan2(+matrix[1], +matrix[0]) * (180 / Math.PI));
console.log('2',angle)
return angle >= 0 ? angle : angle + 360;
}
return 0;
}
function rotateMove(event) {
const currentAngle = getRotationAngle(event.clientX, event.clientY);
const deltaAngle = currentAngle - initialAngle;
const newRotationAngle = initialRotationAngle + deltaAngle;
draggableElement.style.transform = `rotate(${newRotationAngle}deg)`;
}
function getRotationAngle(clientX, clientY) {
const rect = draggableElement.getBoundingClientRect();
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
const angle = Math.atan2(clientY - centerY, clientX - centerX) * (180 / Math.PI);
return angle;
}
function rotateEnd() {
document.removeEventListener('mousemove', rotateMove);
document.removeEventListener('mouseup', rotateEnd);
}
rotateHandle.addEventListener('mousedown', rotateStart);
<div id="draggable" style="width: 100px; height: 100px; background-color: blue;">
<div class="rotate-handle"></div>
</div>
#draggable {
position: absolute;
}
.rotate-handle {
width: 20px;
height: 20px;
background-color: red;
position: absolute;
bottom: -10px;
right: -10px;
cursor: pointer;
}