JSFiddle - React, Tailwind, and code Playground
HTML
<!-- Visualization of perpendicular line computation -->
<!-- http://stackoverflow.com/a/133952/1790054 -->
<!-- Author: Kevin Jurkowski, 04/08/15 -->
<canvas></canvas>
CSS
html, body, canvas {
width: 200px;
height: 200px;
margin: 0;
}
canvas {
background: #000;
}
JavaScript
// Set the position of point A and point B
var ax = 50;
var ay = 150;
var bx = 150;
var by = 50;
// Drawing setup
var canvas = document.getElementsByTagName('canvas')[0];
var context = canvas.getContext('2d');
context.canvas.width = 200;
context.canvas.height = 200;
context.strokeStyle = '#fff';
context.lineWidth = 2;
context.beginPath();
context.moveTo(ax, ay);
context.lineTo(bx, by);
context.stroke();
// Calculate perpendicular offset
var dx = ax - bx;
var dy = ay - by;
var dist = Math.sqrt(dx * dx + dy * dy);
var offset = dist / 4;
var normX = dx / dist;
var normY = dy / dist;
var xPerp = offset * normX;
var yPerp = offset * normY;
// Create perpendicular points
var cx = ax + yPerp;
var cy = ay - xPerp;
var dx = ax - yPerp;
var dy = ay + xPerp;
var ex = bx - yPerp;
var ey = by + xPerp;
var fx = bx + yPerp;
var fy = by - xPerp;
// Draw perpendicular lines
context.moveTo(cx, cy);
context.lineTo(dx, dy);
context.stroke();
context.moveTo(ex, ey);
context.lineTo(fx, fy);
context.stroke();