Search code examples
javascriptmathcanvastrigonometryangle

Drawing a line within boundaries from point (x, y) with a given angle


I am trying to draw a line on JavaScript canvas. I have two points A and B (as shown in the picture).

Points A and B

I use this code to find the angle between these two points:

// p1 is point A and p2 is point B    
var theta = Math.atan2(p2.y - p1.y, p2.x - p1.x);

Now I want to draw a line from point A till the end of the canvas and I also want to get the point where the line ends (point C in the picture).

enter image description here

Can this be achieved using the angle and size(width & height) of the canvas?


Solution

  • It is possible to solve this problem without trigonometric functions. At first construct parametric representation of given AB ray:

     x = A.X + dx * t
     y = A.Y + dy * t
       where
     dx = B.X - A.X
     dy = B.Y - A.Y
    

    The check what edge will be intersected first (with smaller t value):

    //potential border positions    
    if dx > 0 then
       ex = width
    else
       ex = 0
    
    if dy > 0 then
       ey = height
    else
       ey = 0
    
    //check for horizontal/vertical lines 
    if dx = 0 then
        return cx = A.X,  cy = ey
    
    if dy = 0 then
        return cy = A.Y,  cx = ex
    
    
    //in general case find parameters of intersection with horizontal and vertical edge
    tx = (ex - A.X) / dx
    ty = (ey - A.Y) / dy
    
    //and get intersection for smaller parameter value
    if tx <= ty then
       cx = ex
       cy = A.Y + tx * dy
    else
       cy = ey
       cx = A.X + ty * dx
    
    return cx, cy
    

    Results for Width = 400, Height = 300, fixed A point and various B points:

    100:100 - 150:100   400: 100
    100:100 - 150:150   300: 300
    100:100 - 100:150   100: 300
    100:100 - 50:150     0: 200
    100:100 - 50:100     0: 100
    100:100 - 50:50     0:   0
    100:100 - 100:50   100:   0
    100:100 - 150:50   200:   0