Figuring out new X and Y based on rotation

怎甘沉沦 提交于 2021-01-29 12:05:09

问题


I'm nuilding a graphical editor where you can select elements, scale them, rotate, resize etc. One thing I've been stuck on is positioning an element after it's rotated. I have the following javascript class that handles resizing:

const rotateCoords = (x, y, rotation) => {
    const rad = (rotation * Math.PI) / 180
    return {
        y: y * Math.cos(rad) - x * Math.sin(rad),
        x: x * Math.cos(rad) + y * Math.sin(rad),
    }
}

export default (
    e,
    ratio,
    resizeDirection,
    resizeMouseX,
    resizeMouseY,
    zoomScale,
    rotation
) => {
    let resizeMouseX = e.pageX - resizeMouseX
    let resizeMouseY = e.pageY - resizeMouseY

    const newResize = rotateCoords(resizeX, resizeY, rotation)
    resizeX = newResize.x
    resizeY = newResize.y

    let x = 0,
        y = 0,
        width = 0,
        height = 0

    if (resizeDirection === 'r') {
        width = resizeX
    }

    if (resizeDirection === 'l') {
        x = resizeX
        width = -resizeX
    }

    if (resizeDirection === 't') {
        y = resizeY
        height = -resizeY
    }

    if (resizeDirection === 'b') {
        height = resizeY
    }

    if (resizeDirection === 'tr') {
        width = resizeX * ratio
        height = resizeX
        y = -resizeX
    }

    if (resizeDirection === 'br') {
        width = resizeX * ratio
        height = resizeX
    }

    if (resizeDirection === 'bl') {
        width = -resizeX * ratio
        height = -resizeX
        x = resizeX * ratio
    }

    if (resizeDirection === 'tl') {
        width = -resizeX * ratio
        height = -resizeX
        x = resizeX * ratio
        y = resizeX
    }

    return {
        x: x / zoomScale,
        y: y / zoomScale,
        width: width / zoomScale,
        height: height / zoomScale,
    }
}

The different conditions resize the element container based on the anchor that's dragged (bottom left, top right etc.) They will return something like (x: -2, y: 1) or (width: -2, height: 0) based on which anchor is dragged. This works fine when the element is at 0 rotation. However when the element is rotated (for example transform: rotate(30deg), the x and y get out of whack and the element starts floating around in different directions based on it's rotational angle. I'm assuming I need to do some calculation on the returned X and Y to have it stay in place. Could anyone please help me figure this out, it would be much appreciated!

来源:https://stackoverflow.com/questions/60058988/figuring-out-new-x-and-y-based-on-rotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!