Search code examples
javamathvectorjava-canvas

How to truncate a line between 2 points?


I want to draw a line on a canvas. Therefore I use two clicks from the user to define start point S and end point E.

ctx.moveTo(sx, sy);
ctx.lineTo(ex, ey);

I further want to substract a static offset on both sides of the line, eg static int offset = 10; My problem is: how can I know about the direction (north, east, south, west) to which I have to add or substract the offset?

If the line goes from top to bottom, I would have to apply (0, +10) on the start point S, and (0, -10) on the end point. Getting mor complicated when the line goes diagonal through the coordinate space.

Probably that might be a "simple" mathematical problem, but I'm missing the right keywords to find any solutions.


Solution

  • You just need to use some basic math.

    1. Find the x and y displacements
    2. Find the angle theta
    3. Create a displacement vector
    4. Add or take this from your points

    Let me know if this doesn't work.

    int offset = 10;
    
    int[] point1 = {15, 25}; //start point
    int[] point2 = {42, 37}; //end point
    
    int xDisplacement = point2[0] - point1[0];
    int yDisplacement = point2[1] - point1[1];
    
    double theta = Math.toDegrees(Math.atan2(yDisplacement, xDisplacement));        
    
    double[] diplacementVector = {offset*Math.cos(theta), offset*Math.sin(theta)};
    
    point1[0] += diplacementVector[0];
    point1[1] += diplacementVector[1];
    
    point2[0] -= diplacementVector[0];
    point2[1] -= diplacementVector[1];