如何在HTML5 Canvas中找到一条线的坐标 [英] How to find the coordinates of a line in HTML5 Canvas

查看:542
本文介绍了如何在HTML5 Canvas中找到一条线的坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发HTML5中的建筑平面图应用程序。
为此,我需要将门窗放在墙上。
通常,墙(线)不是直的。
如何在移动门图像时发现鼠标是否碰到了墙壁(线条)。
此外,我应该找出要绘制的X,Y和门的角度。
请帮助...

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...

推荐答案

以下是一种方法:

将所有线段(墙)保存在一个数组中。

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});
};

此函数将返回2点之间的距离(2点为鼠标位置,

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));
}

最后,google内置javascript Math。 atan2 来获得你墙的角度作为窗口的角度。

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

祝你的项目顺利!

这篇关于如何在HTML5 Canvas中找到一条线的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆