javascript - 按顺时针方向排序点

标签 javascript math point

如果我有一个点列表 [(x1,y1), (x2,y2), (x3,y3)...] 有什么方法可以安排它们顺时针方向?

顺时针方向是指相对于形状中心的顺时针方向。

最佳答案

首先,您必须找到由您的点定义的形状的中心,因为旋转将相对于该点定义。

然后您必须计算点相对于中心和 x 轴的 Angular 。 要计算 Angular ,您可以使用 Math.atan2(y - center.y, x - center.x)

然后使用 Array.sort 按 Angular 对点进行排序。

一旦点被正确排序,您应该能够绘制一条连接点且不与自身相交的线。我用 Canvas 制作了一个演示。起点用正方形显示。我已经绘制了转换为您点的质心的 x/y 轴。我还添加了将点连接到质心的线以具体化它们的 Angular 。

const width = 250;
const height = 250;

// Random points
const points = Array.from({ length: 20 }, () =>
  ({ x: Math.random() * width, y: Math.random() * height })
);

// Get the center (mean value) using reduce
const center = points.reduce((acc, { x, y }) => {
  acc.x += x / points.length;
  acc.y += y / points.length;
  return acc;
}, { x: 0, y: 0 });

// Add an angle property to each point using tan(angle) = y/x
const angles = points.map(({ x, y }) => {
  return { x, y, angle: Math.atan2(y - center.y, x - center.x) * 180 / Math.PI };
});

// Sort your points by angle
const pointsSorted = angles.sort((a, b) => a.angle - b.angle);

// Draw them
const canvas = document.querySelector('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
let lastPoint = pointsSorted[0];

ctx.fillRect(lastPoint.x, lastPoint.y, 5, 5);

ctx.beginPath();
ctx.moveTo(0, center.y);
ctx.lineTo(width, center.y);
ctx.strokeStyle = 'black';
ctx.stroke();

ctx.beginPath();
ctx.moveTo(center.x, 0);
ctx.lineTo(center.x, height);
ctx.strokeStyle = 'black';
ctx.stroke();  

pointsSorted.forEach(({ x, y }) => {
  ctx.beginPath();
  ctx.moveTo(lastPoint.x, lastPoint.y);
  ctx.lineTo(x, y);
  ctx.strokeStyle = 'red';
  ctx.stroke();  
  
  ctx.fillRect(x, y, 2, 2);
  
  ctx.beginPath();
  ctx.moveTo(center.x, center.y);
  ctx.lineTo(x, y);
  ctx.strokeStyle = 'grey';
  ctx.stroke();  
  
  lastPoint = { x, y };
});
canvas {
  border: 1px solid black;
}
<canvas></canvas>

希望对您有所帮助!

关于javascript - 按顺时针方向排序点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54719326/

相关文章:

javascript - 在内存游戏中点击卡片不会翻转它

javascript - 在 Ember 模板中呈现 {{content}} 时出现问题

java - 平方求幂

javascript - 如何在方表中找到一个数字所属的一组数字的索引?

c# - 如何将一个 3D 点与另一个 3D 点的距离调整给定距离

matlab - 使用 getpts 获取选定的点

Javascript:是否可以将字符串转换为数组的数组?

javascript - 网页 View 后退按钮

javascript - JS 中的简单数学加法给出错误结果

mysql - mysql POINT 坐标的导出/导入问题