我有一个 PNG 序列的 360 图像(每旋转度 1 个图像)。我目前有一个 React 组件,它根据鼠标在窗口内的位置呈现当前的旋转度数,其中 x = 0 是 rotation = 1,x = window.innerWidth
是 rotation = 360。
// Map a set of min/max values to another set of min/max values based on the given value
const map = (value, x1, y1, x2, y2) => (value - x1) * (y2 - x2) / (y1 - x1) + x2;
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.pointerDown = true;
};
handlePointerUp = () => {
this.pointerDown = false;
};
handlePointerMove = event => {
if (!this.pointerDown) {
return;
}
const rotation = Math.round(map(event.pageX, 0, window.innerWidth, 1, 360));
this.setState({rotation});
};
render() {
return <img src={`/img/rotation/${this.state.rotation}.png`}/>
}
}
我遇到的问题是旋转跳跃,我从屏幕中间开始拖动,图像跳到 180 度。我正在努力让它根据最后的旋转位置旋转。我希望它根据我从 startX 位置移动的距离进行旋转。这是可以用数学来完成的事情吗?
最佳答案
当用户开始拖动时存储当前旋转并将偏移量用作增量而不是绝对旋转。
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`}/>
}
}
关于javascript - 360度PNG序列拖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56837177/