简体   繁体   English

如何在HTML5 Canvas中查找线的坐标

[英]How to find the coordinates of a line in HTML5 Canvas

I am developing a Building Plan Drawing Application in HTML5. 我正在开发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. 此外,我应该找到要绘制的门的X,Y和角度。 Please help... 请帮忙...

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). 并且此函数将返回2个点之间的距离(这2个点是鼠标位置和墙上计算出的点)。

// 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. 最后,用谷歌内置的JavaScript Math.atan2获取墙的角度,将其用作窗口的角度。

Good luck with your project! 祝您项目顺利!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM