在html画布中,我绘制了一条从点A开始到点B结束的线。
给定点C,我应该画一条垂直于A和B且从C穿过的线。
下面是我创建从A和B传递的线的方式(将点作为输入,在此示例中,为方便起见,它们由变量提供。
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(50, 100);
ctx.lineTo(150, 100);
ctx.stroke();
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
现在给定C(例如,C = 80、130),我想画一条与A和B之间的线垂直并且从C穿过的线
如何计算允许创建此线的点?
例如:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(50, 100);
ctx.lineTo(150, 100);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(80, 10);
ctx.lineTo(80, 130);
ctx.arc(80, 130, 2, 0, 360, false); // C
ctx.stroke();
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
非常感谢您的帮助!
最佳答案
在不平凡的情况下(线不是垂直或水平的),您只需要知道垂直线的斜率在该线的斜率上是负一。我希望下面的代码段能对您有所帮助。
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var pointA = {
x: 0.0,
y: 0.0
};
var pointB = {
x: 200.0,
y: 150.0
};
var pointC = {
x: 80.0,
y: 130.0
};
var pointD = {
x: 0.0,
y: 0.0
};
if (pointA.y == pointB.y) { // AB is horizontal
pointD.x = pointC.x
pointD.y = pointA.y
} else if (pointA.x == pointB.x) { // AB is vertical
pointD.x = pointA.x
pointD.y = pointC.y
} else { // need some geometry
var gradientOfAB = (pointA.y - pointB.y) / (pointA.x - pointB.x);
var interceptOfAB = pointA.y - gradientOfAB * pointA.x;
var gradientOfCD = -1 / gradientOfAB;
var interceptOfCD = pointC.y - gradientOfCD * pointC.x;
pointD.x = (interceptOfAB - interceptOfCD) / (gradientOfCD - gradientOfAB);
pointD.y = gradientOfCD * pointD.x + interceptOfCD;
}
ctx.beginPath();
ctx.moveTo(pointA.x, pointA.y);
ctx.lineTo(pointB.x, pointB.y);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(pointD.x, pointD.y);
ctx.lineTo(pointC.x, pointC.y);
ctx.arc(pointC.x, pointC.y, 2, 0, 360, false);
ctx.stroke();
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
关于javascript - Canvas HTML |跟踪垂直于两点并经过一个点的线,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59283670/