废话不多说,直接上代码
html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<style>
#app {
width: 500px;
height: 500px;
background: #000;
margin: 200px auto;
}
</style>
</head>
<body>
<div id="app"></div>
<script src="./index.js"></script>
</body>
</html>
JS部分
let currentAngle = 0;// 当前的角度
let oldAngle = 0; // 之前旧的角度
let lastAngles = [0, 0, 0]; // 判断旋转的方向
let startX, startY; // 开始的位置
let positionCallbacks = []
let wheelWidth, wheelHeigh, wheelX, wheelY // 方块的高宽,旋转的位置
let startAngle = 0 // 开始的角度
let isSpinning //是否方块在旋转
let isDragging // 是否抓住不放
calculatePositions()
function calculatePositions() { // 计算方块的宽高,选旋转的中心位置
wheelWidth = $('#app').width(); // 获取元素的宽度
wheelHeight = $('#app').height(); // 获取元素的高度
let offset = $('#app').offset()
wheelX = offset.left + wheelWidth / 2; // 元素旋转的中心点x
wheelY = offset.top + wheelHeight / 2; // 元素旋转的饿中心点y
}
function grab(x, y) {
if (!isSpinning) { // 如果没有旋转方块
isDragging = true // 鼠标点击小方块
startAngle = calculateAngle(x, y) // 计算方块开始旋转角度
}
}
function calculateAngle(currentX, currentY) { // 计算角度
let xLength = currentX - wheelX;
let yLength = currentY - wheelY;
let angle = Math.atan2(xLength, yLength) * (180 / Math.PI);
return 365 - angle;
}
function move(x, y) { // 移动时候的处理
if (!isDragging) return // 如果鼠标没有在方块内按下,就不执行
lastAngles.shift();// 删除第一个角度
lastAngles.push(currentAngle) // 传入当前的旋转角度
let deltaAngle = calculateAngle(x, y) - startAngle; // 计算运动后角的角度
currentAngle = deltaAngle + oldAngle // 当前的角度
render(currentAngle) //旋转图形至当前角度
}
function onRelease() {
if (isDragging) {
isDragging = false; // 鼠标放开
oldAngle = currentAngle; // 将当前位置记录
let speed = lastAngles[0] - lastAngles[2]; // 起始角度差
giveMoment(speed);
}
}
function giveMoment(speed) { // 惯性旋转
if (speed >= 0.1) { // 逆时针旋转
speed -= 0.1;
// setTimeout(function () {
// giveMoment(speed)
// })
window.requestAnimationFrame(giveMoment.bind(this, speed)) // 优化的动画
isSpinning = true;// 正在旋转
}
else if (speed <= -0.1) { // 顺时针旋转
speed += 0.1;
// setTimeout(function () {
// giveMoment(speed)
// })
window.requestAnimationFrame(giveMoment.bind(this, speed)) //动画
isSpinning = true; // 正在旋转
}
else {
isSpinning = false; // 旋转结束
}
oldAngle -= speed;
render(oldAngle);
}
function render(deg) {
// 旋转图形
$('#app').css('transform', `rotate(${deg}deg)`)
}
$('#app').mousedown(function (e) {
// 鼠标在方块内点击开启旋转事件
if (e.which == 1) {
grab(e.clientX, e.clientY)
}
})
$(window).mousemove(function (e) {
if (e.which == 1) {
move(e.clientX, e.clientY);
}
})
$(window).mouseup(function () {
onRelease()
})