问题
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 if my mouse has touched the walls (lines) while moving the door Image. Moreover, I should find the X, Y and angle of the door to be drawn. Please help...
回答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 this
var line={x0:50,y0:50,x1:150,y1:150};
// calculate the closest point on the line to [x,y]
function getClosestPointOnLine(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 points
function distance(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!
来源:https://stackoverflow.com/questions/23610167/how-to-find-the-coordinates-of-a-line-in-html5-canvas