在以下设置中,如何绘制一条穿过两点的“无限”线?



var context = document.getElementById("canvas").getContext("2d");

var point1 = {
    x : 120,
    y : 100,
};

var point2 = {
    x : 250,
    y : 300,
};

// mark points in the canvas
context.fillStyle = "red";
context.beginPath();
context.arc(point1.x + 0.5, point1.y + 0.5, 2, 0, 2 * Math.PI);
context.fill();
context.beginPath();
context.arc(point2.x + 0.5, point2.y + 0.5, 2, 0, 2 * Math.PI);
context.fill();

// draw a line between two points
context.beginPath();
context.moveTo(point1.x, point1.y);
context.lineTo(point2.x, point2.y);
context.stroke();

// draw an "infinite" line that passes through two points
// ??

body {
    font-family: sans-serif;
    box-sizing: border-box;
    background-color: hsl(0, 0%, 90%);
}
canvas {
    display: block;
    margin: 20px;
    background: white;
    box-shadow: 0 0 1px rgba(0,0,0,.2),
                0 0 3px rgba(0,0,0,.15),
                0 1px 2px rgba(0,0,0,.15);
}

<canvas id="canvas" width="400" height="400"></canvas>





我知道我需要计算在同一路径上但在视图(画布)之外的新坐标,并在它们之间绘制一条线以伪造一条无限线。

这些新坐标不必一定在画布的边缘。我认为这需要额外的计算。所以我在想类似

current position ± canvas diagonal (max distance in canvas)


只是要确保新坐标始终在画布之外,并跳过多余的计算。

如何计算这些新坐标?

最佳答案

回到代数课,您可以计算出斜率并进行截距,然后使用它在画布边缘上绘制点。如果它们超出了画布的边界,它将创建一条从边缘延伸的线。

但是请注意,这不支持水平或垂直线,您必须添加额外的检查以覆盖这些实例。本质上,如果斜率为0,则只需在两点的y值处从0到canvas.width画一条线,如果未定义,则在x值从0到canvas.height画一条线。两点。



var context = document.getElementById("canvas").getContext("2d");

var point1 = {
    x : 120,
    y : 100,
};

var point2 = {
    x : 250,
    y : 300,
};

var slope = (point2.y - point1.y)/(point2.x - point1.x)
//y = mx + b | b = y - mx
var intercept = point2.y - (slope * point2.x)

function getY(x){ return (slope * x) + intercept; }
function getX(y) { return (y - intercept)/slope; }

// mark points in the canvas
context.fillStyle = "red";
context.beginPath();
context.arc(point1.x + 0.5, point1.y + 0.5, 2, 0, 2 * Math.PI);
context.fill();
context.beginPath();
context.arc(point2.x + 0.5, point2.y + 0.5, 2, 0, 2 * Math.PI);
context.fill();

// draw a line between two points
context.beginPath();
context.moveTo(getX(0), 0);
context.lineTo(point1.x, point1.y);
context.lineTo(point2.x, point2.y);
context.lineTo(getX(context.canvas.height), context.canvas.height);
context.stroke();

// draw an "infinite" line that passes through two points
// ??

body {
    font-family: sans-serif;
    box-sizing: border-box;
    background-color: hsl(0, 0%, 90%);
}
canvas {
    display: block;
    margin: 20px;
    background: white;
    box-shadow: 0 0 1px rgba(0,0,0,.2),
                0 0 3px rgba(0,0,0,.15),
                0 1px 2px rgba(0,0,0,.15);
}

<canvas id="canvas" width="400" height="400"></canvas>

09-19 21:07