Skip to content Skip to sidebar Skip to footer

How To Find The Coordinates Of A Line In Html5 Canvas

I am developing a Building Plan Drawing Application in HTML5. For that I needed to place the doors and windows on walls. Usually, the walls (lines) are not straight. How can I find

Solution 1:

Here's one way:

Save all your line segments (walls) in an array.

var walls=[];

var wall={x0:50,y0:50,x1:150,y1:150};

walls.push(wall);

When you are dragging your window into place, compare the mouse position to the nearest point on every line segment (wall). Place the window on whichever wall is closest to the mouse.

This function will give you the closest point to the mouse on any given line segment:

// given a line defined like thisvar line={x0:50,y0:50,x1:150,y1:150};

// calculate the closest point on the line to [x,y]functiongetClosestPointOnLine(line,x,y) {
    //
    lerp=function(a,b,x){ return(a+x*(b-a)); };
    var dx=line.x1-line.x0;
    var dy=line.y1-line.y0;
    var t=((x-line.x0)*dx+(y-line.y0)*dy)/(dx*dx+dy*dy);
    t=Math.min(1,Math.max(0,t));
    var lineX=lerp(line.x0, line.x1, t);
    var lineY=lerp(line.y0, line.y1, t);
    return({x:lineX,y:lineY});
};

And this function will return the distance between 2 points (those 2 points being the mouse position and the calculated point on a wall).

// get distance between 2 pointsfunctiondistance(x0,y0,x1,y1){
    var dx=x1-x0;
    var dy=y1-y0;
    return(Math.sqrt(dx*dx+dy*dy));
}

Finally, google the built-in javascript Math.atan2 to get the angle of your wall to use as the angle of your window.

Good luck with your project!

Post a Comment for "How To Find The Coordinates Of A Line In Html5 Canvas"