矩形中间点和四个顶点之前的转换问题

记录一个简单的算法问题

1.已知一个矩形的中心点坐标 旋转角度 长宽 求四个点的坐标

  • @param cx 旋转中心点 x 坐标
  • @param cy 旋转中心点 y 坐标
  • @param arrowAngle 旋转角度
  • @param scaleW 宽
  • @param scaleH 高
 //角度转换
    let X1, Y1, X2, Y2, X3, Y3, X4, Y4;
    let angle = (180-arrowAngle) * Math.PI / 180,
    back_left = {
      x: cx - scaleW / 2,
      y: cy + scaleH / 2,
    },
    back_right = {
      x: cx - scaleW / 2,
      y: cy - scaleH / 2,
    },
    front_left = {
      x: cx + scaleW / 2,
      y: cy + scaleH / 2,
    },
    front_right = {
      x: cx + scaleW / 2,
      y: cy - scaleH / 2,
    };
     //按逆时针或者顺时针旋转角度center.x后的四个点坐标
    X1 = (back_right.x - cx) * Math.cos(angle) - (back_right.y - cy) * Math.sin(angle) + cx;
    Y1 = (back_right.y - cy) * Math.cos(angle) + (back_right.x - cx) * Math.sin(angle) + cy;
    X2 = (back_left.x - cx) * Math.cos(angle) - (back_left.y - cy) * Math.sin(angle) + cx;
    Y2 = (back_left.y - cy) * Math.cos(angle) + (back_left.x - cx) * Math.sin(angle) + cy;
    X3 = (front_left.x - cx) * Math.cos(angle) - (front_left.y - cy) * Math.sin(angle) + cx;
    Y3 = (front_left.y - cy) * Math.cos(angle) + (front_left.x - cx) * Math.sin(angle) + cy;
    X4 = (front_right.x - cx) * Math.cos(angle) - (front_right.y - cy) * Math.sin(angle) + cx;
    Y4 = (front_right.y - cy) * Math.cos(angle) + (front_right.x - cx) * Math.sin(angle) + cy;
    back_right=[X2,Y2];
    back_left = [X1,Y1];
    front_left = [X3,Y3];
    front_right = [X4,Y4];
    return [back_left,back_right,front_left,front_right]```

2.已知四个点的坐标,求出中心点的坐标 旋转角度 长宽

fromWeb_x_y([back_left_d3xy,back_right_d3xy,front_left_d3xy,front_right_d3xy]){
    //矩形的高
    let xh = Math.abs(back_left_d3xy[0]-back_right_d3xy[0])
    let yh = Math.abs(back_left_d3xy[1]-back_right_d3xy[1])
    let height = Math.sqrt(Math.pow(xh,2)+Math.pow(yh,2))
    //矩形的宽
    let xw = Math.abs(back_left_d3xy[0]-front_left_d3xy[0])
    let yw = Math.abs(back_left_d3xy[1]-front_left_d3xy[1])
    let width = Math.sqrt(Math.pow(xw,2)+Math.pow(yw,2))
    //选两个点求旋转角度
    let tana = (front_right_d3xy[1] - back_left_d3xy[1]) / (front_right_d3xy[0] - back_left_d3xy[0])
    let angle = 180 * Math.atan(tana) / Math.PI
    //求中心点坐标
    let center_left_d3xy= [(back_left_d3xy[0]+back_right_d3xy[0])/2, (back_left_d3xy[1]+back_right_d3xy[1])/2]
    let center_right_d3xy= [(front_left_d3xy[0]+front_right_d3xy[0])/2, (front_left_d3xy[1]+front_right_d3xy[1])/2]
    let center_d3xy=[(center_left_d3xy[0]+center_right_d3xy[0])/2, (center_left_d3xy[1]+center_right_d3xy[1])/2]

    return {
      center_d3xy: center_d3xy,
      center_PhysicalXY: center_PhysicalXY,
      width: width,
      height: height,
      angle: angle
    }
  }

ps:
1.上边只是简单的转换
2.涉及浮点数的精确度问题,需要另外在计算中加入自己定义的浮点精度
3.涉及物理坐标和平面坐标的转换问题,在每次结果输出之前转换即可,切记注意两个坐标的y轴的方向差异
4.关于角度的象限问题,可在angle后面叠加具体判断

你可能感兴趣的:(js,d3.js,svg)