javascript - 360 度 PNG 序列拖动
问题描述
我有一个包含 360 个图像的 PNG 序列(每旋转度 1 个图像)。我目前有一个 React 组件,它根据窗口内的鼠标位置呈现当前的旋转度数,其中 x = 0 是旋转 = 1,x =window.innerWidth
是旋转 = 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 - 如何解决语法错误:Reactjs 中出现意外的令牌 (100:33)
- javascript - 为什么 webpack 输出总是 main.js?
- python - Python 类练习不适用于父类
- javascript - 是否可以在高图中将百分比放在列的中间?
- c++ - 重复错误sstream:没有这样的文件或目录
- flutter - 飞镖中的最终/常量
- jenkins - JenkinsPipelineUnit 如何与共享声明式管道一起使用?
- python - Python、Selenium 和 2Captcha 解决验证码不起作用
- python - 从 Kivy 和 Python 中的 FileChooserIconView 拖放文件后,在文本输入小部件中获取文件路径
- ios - 利用 iOS 15 的英语字符串语法协议功能