我有一个360幅图像的PNG序列(每旋转1幅图像)。我目前有一个React组件,它根据窗口内的鼠标位置来呈现当前的旋转度,其中x = 0表示rotation = 1,x = {["am","are","hello","how","you","there"]
表示rotation = 360。
window.innerWidth
我遇到的问题是旋转跳动,从屏幕中间开始拖动,图像跳至180度。我正在努力让它根据上一个旋转位置旋转。我希望它根据我从startX位置移动的距离旋转。这可以用数学完成吗?
答案 0 :(得分:3)
在用户开始拖动时存储当前旋转,并将偏移量用作增量而不是绝对旋转。
class Rotation extends Component {
startX = 0;
lastX = 0;
pointerDown = false;
state = {
rotation: 1,
};
componentDidMount() {
window.addEventListener('pointerdown', this.handlePointerDown);
window.addEventListener('pointerup', this.handlePointerUp);
window.addEventListener('pointermove', this.handlePointerMove);
}
handlePointerDown = event => {
this.startX = event.pageX;
this.startRotation = this.state.rotation;
this.pointerDown = true;
};
handlePointerUp = () => {
this.pointerDown = false;
};
handlePointerMove = event => {
if (!this.pointerDown) {
return;
}
// If you want to rotate the other way, invert the subtraction
const offset = 360 * (event.pageX - this.startX) / window.innerWidth;
let newRotation = this.startRotation + offset;
// Need to offset by 1 before the modulo since it works between 0-359
newRotation = ((newRotation - 1) % 360) + 1;
if (newRotation <= 0) newRotation += 360;
this.setState({ rotation: newRotation });
};
render() {
return <img src={`/img/rotation/${this.state.rotation}.png`}/>
}
}