计算线的相同斜率上的点

时间:2018-07-18 18:15:12

标签: javascript

我有几个点,需要确保在同一斜率上的点的长度应仅为100,即从同一方向上的point1到point2。

http://jsfiddle.net/xpvt214o/440613/

这是绘制箭头的代码

function draw(point1, point2, distance, length) {
  // slope is dx/dy
  let dx = point2[0] - point1[0]
  let dy = point2[1] - point1[1]
  let v_norm = Math.sqrt(dx ** 2 + dy ** 2)

  // point on line at distance
  let point_on_line = [point2[0] - distance * dx / v_norm, point2[1] - distance * dy / v_norm]

  // endpoints of arrows at length above point (the distance from the original line
  let point_below = [point_on_line[0] - length * -dy / v_norm, point_on_line[1] - length * dx / v_norm, ]
  let point_above = [point_on_line[0] + length * -dy / v_norm, point_on_line[1] + length * dx / v_norm, ]

  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');
  ctx.fillStyle="#FF0000";
  ctx.beginPath();
  ctx.moveTo(...point1);
  ctx.lineTo(...point2);
  ctx.moveTo(...point_above)
  ctx.lineTo(...point2)
  ctx.lineTo(...point_below)
  ctx.stroke();
}

draw([100, 100], [200, 150], 90, 10)
/* draw([100, 100], [300, 150], 20, 10)
draw([100, 100], [150, 10], 20, 10)
draw([100, 100], [90, 150], 20, 10)
draw([100, 100], [200, 100], 20, 10)
draw([100, 100], [5, 10], 20, 10 */

0 个答案:

没有答案