首页 > 解决方案 > 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 位置移动的距离旋转。这是可以用数学完成的吗?

标签: javascriptreactjsmath

解决方案


当用户开始拖动时存储当前旋转并将偏移量用作增量而不是绝对旋转。

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`}/>
    }
}

推荐阅读