从点 (x, y) 以给定角度在边界内绘制一条线 [英] Drawing a line within boundaries from point (x, y) with a given angle
问题描述
我正在尝试在 JavaScript 画布上画一条线.我有两个点 A 和 B(如图所示).
I am trying to draw a line on JavaScript canvas. I have two points A and B (as shown in the picture).
我用这段代码来求这两点之间的角度:
I use this code to find the angle between these two points:
// p1 is point A and p2 is point B
var theta = Math.atan2(p2.y - p1.y, p2.x - p1.x);
现在我想从点 A 到画布的末端画一条线,我还想得到线结束的点(图片中的点 C).
Now I want to draw a line from point A till the end of the canvas and I also want to get the point where the line ends (point C in the picture).
这可以使用画布的角度和大小(宽度和高度)来实现吗?
Can this be achieved using the angle and size(width & height) of the canvas?
推荐答案
可以不用三角函数来解决这个问题.首先构造给定AB射线的参数表示:
It is possible to solve this problem without trigonometric functions. At first construct parametric representation of given AB ray:
x = A.X + dx * t
y = A.Y + dy * t
where
dx = B.X - A.X
dy = B.Y - A.Y
检查哪个边会先相交(t值较小):
The check what edge will be intersected first (with smaller t value):
//potential border positions
if dx > 0 then
ex = width
else
ex = 0
if dy > 0 then
ey = height
else
ey = 0
//check for horizontal/vertical lines
if dx = 0 then
return cx = A.X, cy = ey
if dy = 0 then
return cy = A.Y, cx = ex
//in general case find parameters of intersection with horizontal and vertical edge
tx = (ex - A.X) / dx
ty = (ey - A.Y) / dy
//and get intersection for smaller parameter value
if tx <= ty then
cx = ex
cy = A.Y + tx * dy
else
cy = ey
cx = A.X + ty * dx
return cx, cy
宽度 = 400、高度 = 300、固定 A 点和各种 B 点的结果:
Results for Width = 400, Height = 300, fixed A point and various B points:
100:100 - 150:100 400: 100
100:100 - 150:150 300: 300
100:100 - 100:150 100: 300
100:100 - 50:150 0: 200
100:100 - 50:100 0: 100
100:100 - 50:50 0: 0
100:100 - 100:50 100: 0
100:100 - 150:50 200: 0
这篇关于从点 (x, y) 以给定角度在边界内绘制一条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!