<template>
  <div style="width: 600px; height: 300px; background: #dbeede; position: relative">
    <div v-for="(item, index) in points" :key="index">
      <div
        :style="{
          position: 'absolute',
          width: '10px',
          height: '10px',
          backgroundColor: '#000',
          borderRadius: '50%',
          zIndex: 999,
          left: item.x + 'px',
          top: item.y + 'px'
        }"
      ></div>
    </div>
  </div>
  <div style="width: 600px; height: 300px; background: #b3dcff; position: relative">
    <div v-for="(item, index) in mappedPoints" :key="index">
      <div
        :style="{
          position: 'absolute',
          width: '10px',
          height: '10px',
          backgroundColor: '#000',
          borderRadius: '50%',
          zIndex: 999,
          left: item.x + 'px',
          top: item.y + 'px'
        }"
      ></div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const points = ref([
  {
    x: 123.567,
    y: 178.123
  },
  {
    x: 255.567,
    y: 79.123
  },
  {
    x: 382.567,
    y: 178.123
  },
  {
    x: 481.567,
    y: 238.123
  }
])

const mapPointsToLine = (points) => {
  if (points.length < 2) {
    return points
  }
  // 取数组的第一项和最后一项
  const firstPoint = points[0]
  const lastPoint = points[points.length - 1]

  // 计算直线的斜率
  const dx = lastPoint.x - firstPoint.x
  const dy = lastPoint.y - firstPoint.y
  if (dx === 0) {
    // 垂直直线的情况
    return points.map((point, index) => {
      if (index === 0 || index === points.length - 1) {
        return point
      }
      return { x: firstPoint.x, y: point.y }
    })
  }
  const slope = dy / dx
  // 计算直线的截距
  const intercept = firstPoint.y - slope * firstPoint.x

  // 映射其他点到直线上
  return points.map((point, index) => {
    if (index === 0 || index === points.length - 1) {
      return point
    }
    const newY = slope * point.x + intercept
    return { x: point.x, y: newY }
  })
}

const mappedPoints = mapPointsToLine(points.value)
console.log(mappedPoints)
</script>
