我试图在画布上画出一条垂直线,在重新计算一下数学后,我未能在我的代码中实现该公式。
我有一个点p1和点p2画一条直线,但是然后我需要画一条穿过p3的垂直线(预期结果就像图片中的蓝线)
我的代码首先是找到给定两点(p1,p2)的线方程。以下是我如何找到m(坡度)的方法。
double x1=p1.x;
double x2=p2.x;
double y1=p1.y;
double y2=p2.y;
double m=(y2-y1)/(x2-x1);
并且要找到垂直线的斜率,我正在编写如下代码
//this code I expected to transform the previous m to negative reciprocal.
double invertedM = ( 1 / m ) * -1;
然后我必须用我的第三个点p3找到新的[[c(y-intercept)以形成新的线方程。并代入y1 = 0和y2 = screeen_height绘制穿过p3的垂直线
double invertedC = p3.y / (invertedM * p3.x) ;
//get x give y = 0
qy1 = 0 ;
double findX1 = (qy1-invertedC)/invertedM;
Point answerPoint1 = Point(findX1,qy1);
//get x given y = screenheight
qy2 = screenheight ;
double findX2 = (qy2-invertedC)/invertedM;
Point answerPoint2 = Point(findX2,qy2);
但是以某种方式我得到的结果虽然是垂直的,但没有穿过p3。
class Shape {
constructor(ctx, coord) {
this.ctx = ctx;
this.coord = coord;
let v = {
x: coord[1].x - coord[0].x,
y: coord[1].y - coord[0].y
}
this.angle = Math.atan2(v.y, v.x)
}
drawLine(coord, color) {
this.ctx.beginPath();
this.ctx.moveTo(coord[0].x, coord[0].y);
this.ctx.lineTo(coord[1].x, coord[1].y);
this.ctx.strokeStyle = color;
this.ctx.stroke();
}
draw(pos) {
this.drawLine(this.coord, "black");
var x = pos.x + 200 * Math.cos(this.angle + Math.PI / 2)
var y = pos.y + 200 * Math.sin(this.angle + Math.PI / 2)
this.drawLine([{x,y,}, pos], "red");
}
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
const canvas = document.getElementById('c');
const ctx = canvas.getContext('2d');
shape = new Shape(ctx, [{x: 0,y: 50}, {x: 200,y: 100}])
shape.draw({x: 100,y: 0})
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
ctx.clearRect(0, 0, canvas.width, canvas.height)
shape.draw(mousePos);
}, false);
<canvas id="c" width=200 height=160 style="border:2px solid #a7a4a4;"></canvas>
给出两点,我们可以计算出角度:this.angle = Math.atan2(v.y, v.x)
然后添加90度或弧度(Math.PI / 2),即垂直线的角度。
问题尚不清楚,垂直线应位于(p3)的位置,因此我将其相对于鼠标设置为垂直方向,如果运行该代码段并将鼠标移到画布上,则应该从鼠标位置向下看到一条线。
我使用了HTML画布,但是可以将其应用于任何其他画布。