第一种拖拽元素旋转:
<!DOCTYPE html>
<html>
<head>
<style>
body{
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
.draggable {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
cursor: move;
transform-origin: center center;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="draggable" id="draggable"></div>
<script>
const draggable = document.getElementById('draggable');
let dragging = false;
let startAngle = 0;
let currentRotation = 0;
let centerX, centerY;
draggable.addEventListener('mousedown', (e) => {
dragging = true;
centerX = draggable.offsetLeft + draggable.clientWidth / 2;
centerY = draggable.offsetTop + draggable.clientHeight / 2;
startAngle = Math.atan2(centerY - e.clientY, centerX - e.clientX) * 180 / Math.PI - currentRotation;
});
document.addEventListener('mousemove', (e) => {
if (dragging) {
const angle = Math.atan2(centerY - e.clientY, centerX - e.clientX) * 180 / Math.PI;
const rotation = angle - startAngle;
currentRotation = rotation;
draggable.style.transform = `rotate(${rotation}deg)`;
}
});
document.addEventListener('mouseup', () => {
dragging = false;
});
</script>
</body>
</html>
第二种拖拽按钮使元素旋转:
<!DOCTYPE html>
<html>
<head>
<style>
body{
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
.draggable {
width: 100px;
height: 100px;
background-color: red;
position: relative;
transform-origin: center center;
}
.rotate-button {
position: absolute;
top: -20px;
left: 50%;
transform: translateX(-50%);
background-color: blue;
width: 30px;
height: 30px;
cursor: move;
}
</style>
</head>
<body>
<div class="draggable" id="draggable">
<div class="rotate-button" id="rotateButton"></div>
</div>
<script>
const draggable = document.getElementById('draggable');
const rotateButton = document.getElementById('rotateButton');
let dragging = false;
let startAngle = 0;
let currentRotation = 0;
let centerX, centerY;
rotateButton.addEventListener('mousedown', (e) => {
e.stopPropagation();
dragging = true;
centerX = draggable.offsetLeft + draggable.clientWidth / 2;
centerY = draggable.offsetTop + draggable.clientHeight / 2;
startAngle = Math.atan2(centerY - e.clientY, centerX - e.clientX) * 180 / Math.PI - currentRotation;
});
document.addEventListener('mousemove', (e) => {
if (dragging) {
const angle = Math.atan2(centerY - e.clientY, centerX - e.clientX) * 180 / Math.PI;
const rotation = angle - startAngle;
currentRotation = rotation;
draggable.style.transform = `rotate(${rotation}deg)`; // 应用旋转角度
}
});
document.addEventListener('mouseup', () => {
dragging = false;
});
</script>
</body>
</html>
atan2
是一个数学函数,用于计算两个坐标值的反正切(arctangent)值。它通常用于计算两点之间的角度。在 JavaScript 中,atan2
是 Math
对象的一个方法,表示为 Math.atan2(y, x)
。它接受两个参数:y
和 x
,分别表示点 (x, y)
的纵坐标和横坐标。
atan2
的返回值是一个表示从 x 轴正向逆时针旋转到点 (x, y)
的弧度值。为了将弧度转换为角度,您可以使用以下公式:
degrees = radians * (180 / Math.PI)
atan2
函数在计算几何问题和向量运算中非常有用,例如计算两点之间的角度、旋转物体等。