Home

一些JS数据处理方法

# 根据关键点坐标数组,以1像素为单位生成连续坐标点

推导思路 已知两点,求两点间坐标方法如下,结果为point1-point2

function getLineCoordinates(point1, point2) {
  const coordinates = [];
  const dx = point2.x - point1.x;
  const dy = point2.y - point1.y;
  const steps = Math.max(Math.abs(dx), Math.abs(dy));
 
  for (let i = 0; i <= steps; i++) {
    const x = point1.x + (dx / steps) * i;
    const y = point1.y + (dy / steps) * i;
    coordinates.push({ x: Math.round(x), y: Math.round(y) });
  }
 
  return coordinates;
}
const point1 = { x: 3, y: 1 };
const point2 = { x: 1, y: 1 };
const lineCoordinates = getLineCoordinates(point1, point2);
console.log(lineCoordinates);
//输出结果为
[{x: 3, y: 1},{x: 2, y: 1},{x: 1, y: 1}]

求多个关键点坐标数据之间的连续坐标

function getLineCoordinatesArry(points) {
  const coordinates = [];
  points.forEach((e,index) => {
    let point2,point1;
    if(index == points.length-1){
      //计算最后一项到起点
       point2 = points[0] 
       point1 = points[index]
    }else{
       point2 = points[index+1]
       point1 = points[index]
    
    }

    const dx = point2.x - point1.x;
    const dy = point2.y - point1.y;
    const steps = Math.max(Math.abs(dx), Math.abs(dy));
    console.log('steps',steps)
   
    for (let i = 0; i <= steps; i++) {
    
      const x = point1.x + (dx / steps) * i;
      const y = point1.y + (dy / steps) * i;
      coordinates.push({ x: Math.round(x), y: Math.round(y) });
    }
  });
  return coordinates;
}
const result = getLineCoordinatesArry([{ x: 1, y: 1 },{ x: 5, y: 1 },{ x: 5, y: 3 },{ x: 1, y: 3 }])
const result_unique = [...new Set(result.map(e=> JSON.stringify(e)))].map(e=>JSON.parse(e))
console.log('result_unique', result_unique)