I'm trying to find the red point coordinates in this image where the points are projected on to a line formed by the jagged line's start and end point.
I'm using the code from this article, What are the coordinates of the projected point on a line segment using the perp dot product ?, but it appears that I'm doing something incorrectly. Could someone please help me achieve the result in the above image. Thank you!
const points = [
{ x: 2, y: 2 },
{ x: 3, y: 1 },
{ x: 4, y: 4 },
{ x: 5, y: 3 },
{ x: 6, y: 6 },
{ x: 7, y: 5 },
{ x: 8, y: 6 }
];
const first = points[0];
const last = points.slice(-1)[0];
const d = {
x: last.x - first.x,
y: last.y - first.y
};
function dot_product(pt1,pt2)
{
return pt1.x*pt2.x + pt1.y*pt2.y;
}
function drawChart() {
let projected = [];
for (var i=0; i<points.length; i++)
{
p = points[i];
let e2 = {x:p.x-first.x,y:p.y-first.y};
let dot = dot_product(d,e2);
let len2 = d.x * d.x + d.y * d.y;
let v = {
x: first.x + (dot*d.x)/ len2,
y: first.y + (dot*d.y)/ len2,
}
projected.push(v);
}
chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: false,
theme: "light2",
data: [
{
type: "line",
color: "blue",
lineDashType: "dash",
indexLabelFontSize: 16,
dataPoints: [points[0],points.slice(-1)[0]]
},
{
type: "line",
color: "blue",
indexLabelFontSize: 16,
dataPoints: points
},
{
type: "line",
color: "red",
indexLabelFontSize: 16,
dataPoints: projected
}
]
});
chart.render();
}
drawChart();
html
{
font-family: sans-serif;
}
body
{
width: 80%;
position: relative;
}
#chartContainer { height: 400px; width: 320px; }
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer"></div>