canvas绘制求对应点的位置;

canvas绘制求对应点的位置;_第1张图片

1、需求入上图所示,已知连成折线的每个点坐标与折线总长度假设现在为8m,求某个距离假设为3.6m在折线上的坐标;

let points = [{x:19,y:30},......],ropelen =8,leakageDistance=3.6;

首先我们可以根据每个坐标点及其勾股定理算出折线在屏幕中实际的总长度;

let i = 0
let sumPointDistance = 0 // 屏幕像素线段总长
while (i < points.length - 1) {
  sumPointDistance += Math.sqrt(
      Math.pow(points[i].x - points[i + 1].x, 2) +
        Math.pow(points[i].y - points[i + 1].y, 2)
    )
    i++
  }

然后根据实际绳长于屏幕长度比例相同得出 3.6米处的绳长与实际3.6米在屏幕像素线段总长比例与8m在屏幕像素线段总长比例一样得出;

 let surplusDistance = (sumPointDistance * leakageDistance) / ropeLen // 当前3.6米对应的屏幕像素长度

如果线段为一条直线,那么3.6m处的点横坐标应该为起点与终点距离surplusDistance乘以两点横坐标与surplusDistance比;纵坐标也一样;
如果是多线段,就一段一段算,如果第一段小于3.6米,那就减去第一段,看剩余的长度与第二段的大小,循环往下,知道最后一段,求出点的位置;

let k = 0;
const leakagePoint = {}
while (k < points.length - 1) {
   // 当前两点之间的距离
   let currentPointDistance = Math.sqrt(
     Math.pow(points[k].x - points[k + 1].x, 2) +
       Math.pow(points[k].y - points[k + 1].y, 2)
   )

   if (surplusDistance <= currentPointDistance) {
     var sinY =
       Math.abs(points[k].y - points[k + 1].y) / currentPointDistance
     var cosX =
       Math.abs(points[k].x - points[k + 1].x) / currentPointDistance
     var leakageY_Distance = surplusDistance * sinY
     var leakageX_Distance = surplusDistance * cosX

     // 如果此点y小于下一个点
     if (points[k].x < points[k + 1].x) {
       leakagePoint.x = points[k].x + leakageX_Distance
     } else {
       leakagePoint.x = points[k].x - leakageX_Distance
     }
     if (points[k].y < points[k + 1].y) {
       leakagePoint.y = points[k].y + leakageY_Distance
     } else {
       leakagePoint.y = points[k].y - leakageY_Distance
     }
     break
   }
   surplusDistance = surplusDistance - currentPointDistance
   k++
 }
 return leakagePoint

求出对应点的坐标;

你可能感兴趣的:(javascript)