In plane $\mathbb{R}^2$, a rectangle $R$ with center $P_2(x_2,y_2)$ and vertices $(x_2 \pm w, y_2 \pm h)$ (sides parallel to axes) is given. We consider the transformation which, to a given point $P_1(x_1,y_1)$ outside the rectangle associates the intersection point $P_3$ of $P_2P_1$ with the sides of the rectangle, as shown on the figure. This kind of problem occurs in computer vision for mapping a scene onto the border of a "vision box".
Is it possible to build an "elegant" algorithm for this transformation $P_1 \rightarrow P_3$, that avoids as possible the consideration of 4 separate cases ?


Translate both points so that the center moves to the origin. Then the edges of the rectangle have equations $$2|X|=w,\\2|Y|=h,$$
and the line from the origin to the given point $(x,y)$ can be expressed as
$$X=tx,Y=ty.$$
Solve for $t$ and keep the smallest value among
$$t=\left|\frac{w}{2x}\right|,t=\left|\frac{h}{2y}\right|.$$
I leave it to you to adjust for the signs. (And don't forget to "untranslate".)
Note that you will have one of $|X|=\dfrac w2$ or $|Y|=\dfrac h2$.