0

将元素移动一个预定义的角度的最好和最优雅的方式是什么,就这样它移动到了它的容器之外?

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

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

元素在其容器外的示例移动

4

1 回答 1

0

我通过使用Find rectangle boundary point 中的函数来解决它,该函数与不在矩形中间的点成一定角度

只是稍微修改了函数,所以元素完全在容器之外。

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;
}

于 2019-03-14T12:01:47.580 回答