将元素移动定义的角度以将其移出容器

时间:2019-03-13 15:45:05

标签: javascript math sin cos

将元素移动到容器外部,以预定角度移动最好,最优雅的方法是什么?

如下图所示,我想移动元素,使其位于容器的外部。我只想定义一个特定的角度即可实现。 (忽略这里的度数范围,只是为了说明我的情况)

该元素应该能够在所有角度(0-359°)移动

Example movement of the element outside of its container

1 个答案:

答案 0 :(得分:0)

我使用Find rectangle boundary point at an angle from point that is not in the middle of the rectangle中的函数解决了这个问题。

只需稍微修改一下功能,即可将元素完全放在容器之外。

function getEdgePointBasedOnAngle(position: Position, elementSize: Size, angle: number): Position {
    angle = (angle) * (Math.PI / 180);
    const canvasSize: Size = { width: 1, height: 1 };
    const dx = Math.cos(angle);
    const dy = Math.sin(angle);

    // Left border
    if (dx < 1.0e-16) {
        const y = (position.x) * dy / dx + (canvasSize.height - position.y);
        if (y >= 0 && y <= canvasSize.height) {
            return {
            	x: -(elementSize.width / 2) , 
              y: canvasSize.height - y - elementSize.height * -(dy * 0.5);
            };
        }
    }

    // Right border
    if (dx > 1.0e-16) {
        const y = (canvasSize.width - position.x) * dy / dx + position.y;
        if (y >= 0 && y <= canvasSize.height) {
            return {
            	x: canvasSize.width + (elementSize.width / 2),
              y: y + elementSize.height * (dy * 0.5)
            };
        }
    }

    // Top border
    if (dy < 1.0e-16) {
        const x = (position.y) * dx / dy + (canvasSize.width - position.x);
        if (x >= 0 && x <= canvasSize.width) {
            return {
            	x: canvasSize.width - x - elementSize.width * -(dx * 0.5),
              y: -(elementSize.height / 2)
            };
        }
    }

    // Bottom border
    if (dy > 1.0e-16) {
        const x = (canvasSize.height - position.y) * dx / dy + position.x;
        if (x >= 0 && x <= canvasSize.width) {
            return {
            	x: x + elementSize.width * (dx * 0.5), 
              y: canvasSize.height + (elementSize.height / 2)
            };
        }
    }

    return position;
}