Created
March 11, 2022 07:53
-
-
Save wulucxy/d5b8296877654dedf3e0f26a7c9c97ec to your computer and use it in GitHub Desktop.
#canvas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const slope = getSlope(firstPoint, secondPoint); | |
const perpSlope = getPerpSlope(slope); | |
let perpPointOne = findPointOnLine(firstPoint, perpSlope, 10); | |
let perpPointTwo = findPointOnLine(firstPoint, perpSlope, -10); | |
ctx.moveTo(perpPointOne.x, perpPointOne.y); | |
ctx.lineTo(perpPointTwo.x, perpPointTwo.y); | |
perpPointOne = findPointOnLine(secondPoint, perpSlope, 10); | |
perpPointTwo = findPointOnLine(secondPoint, perpSlope, -10); | |
ctx.moveTo(perpPointOne.x, perpPointOne.y); | |
ctx.lineTo(perpPointTwo.x, perpPointTwo.y); | |
ctx.stroke(); | |
function getSlope(pointA, pointB) | |
{ | |
return (pointB.y - pointA.y) / (pointB.x - pointA.x); | |
} | |
function getPerpSlope(slope) | |
{ | |
return -1 / slope; | |
} | |
function findPointOnLine(startPoint, slope, distance) | |
{ | |
const newPoint = { }; | |
if (slope === 0) { | |
newPoint.x = startPoint.x + distance; | |
newPoint.y = startPoint.y; | |
} else if (slope === Infinity) { | |
newPoint.x = startPoint.x; | |
newPoint.y = startPoint.y + distance; | |
} else { | |
dx = (distance / Math.sqrt(1 + (slope * slope))); | |
dy = slope * dx; | |
newPoint.x = startPoint.x + dx; | |
newPoint.y = startPoint.y + dy; | |
} | |
return newPoint; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment