gpt4 book ai didi

javascript - "Infinite"穿过两点的线

转载 作者:行者123 更新时间:2023-11-30 08:21:27 25 4
gpt4 key购买 nike

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

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>

我知道我需要计算在同一路径上但在 View ( Canvas )之外的新坐标,并在它们之间画一条线来伪造一条无限线。

这些新坐标不必位于 Canvas 的边缘。我认为这需要额外的计算。所以我在想类似的事情

current position ± canvas diagonal (max distance in canvas)

只是为了确保新坐标始终在 Canvas 之外,并跳过多余的计算。

如何计算这些新坐标?

最佳答案

回到代数课,您可以计算斜率和截距,并使用它在 Canvas 边缘绘制点。如果它们超出了 Canvas 的边界,它会创建一条延伸到边缘之外的线。

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

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>

关于javascript - "Infinite"穿过两点的线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52937238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com