-1

I have one Line with starting co-ordinate(x1,y1) and ending co-ordinate(x2,y2).

context.beginPath();
context.lineTo(x1,y1);
context.lineTo(x2,y2);
context.stroke()

I want to draw perpendicular line from middle of that line in Canvas Tag.

A Warm reply or guidence will be greatly appreciated.

Djave
  • 8,595
  • 8
  • 70
  • 124
V-Vek P-Tel
  • 77
  • 1
  • 10

2 Answers2

0

To draw a perpendicular line you just need to rotate it 90º, follow this question answered before which contains some example functions to do it, like:

function setTransformToLine(x1, y1, x2, y2) {
  const vx = x2 - x1;   // get the line as vector
  const vy = y2 - y1;
  const len = Math.hypot(vx, vy); // For <= IE11 use Math.sqrt(vx * vx + vy * vy)
  const nx = vx / len; // Normalise the line vector. Making it one
  const ny = vy / len; // pixel long. This sets the scale

  // The transform is the normalised line vector for x axis, y at 90 deg 
  // and origin at line start
  ctx.setTransform(nx, ny, -ny, nx, x1, y1); // set transform

  return len;
}
Ignacio Ara
  • 2,476
  • 2
  • 26
  • 37
  • The Code is working perfect but I want to Draw the perpendicular Line from Middle point of the base Line – V-Vek P-Tel Apr 20 '18 at 14:23
  • Well in that case you need to get the middle, for X `var midX=line.x0+(line.x1-line.x0)*0.50;` and for Y `var midY=line.y0+(line.y1-line.y0)*0.50;` – Ignacio Ara Apr 20 '18 at 14:34
  • I already get the middle point of that base line. I want to draw a perpendicular line from that middle point – V-Vek P-Tel Apr 20 '18 at 15:44
0

The coordinates for the middle of the line are the averages of the coordinates of the ends:

var midX = (x1 + x2) / 2;
var midY = (y1 + y2) / 2;

The directional vector of the perpendicular is the same as the original line, except the coordinates are flipped and one of the coordinates is multiplied by -1 (which one you multiply decides whether the line will be clockwise or anticlockwise from the original). Add that directional vector to the midpoint and you have your perpendicular.

var dx = (x2 - x1);
var dy = (y2 - y1);
context.moveTo(midX, midY);
context.lineTo(midX + dy, midY - dx);
context.stroke();

This will draw a perpendicular that is the same length as your original line. If you want to draw a different length you'll need to adjust the directional vector. Read up on coordinate geometry and vectors for more details.

Máté Safranka
  • 4,081
  • 1
  • 10
  • 22