JSFiddle - React, Tailwind, and code Playground

by Hooman Askari

HTML

<canvas id="myCanvas" width="200" height="100"style="border:1px solid #000000;">
</canvas>

JavaScript

var x1 = 10;
var y1 = 10;

var x2 = 125;
var y2 = 45;

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

// Draw a line.
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();

// Determine line lengths
var xlen = x2 - x1;
var ylen = y2 - y1;

// Determine hypotenuse length
var hlen = Math.hypot(xlen, ylen);

// The variable identifying the length of the `shortened` line.
// In this case 50 units.
var smallerLen = 0;

// Determine the ratio between they shortened value and the full hypotenuse.
var ratio = smallerLen / hlen;

var smallerXLen = xlen * ratio;
var smallerYLen = ylen * ratio;

// The new X point is the starting x plus the smaller x length.
var smallerX = x1 + smallerXLen;

// Same goes for the new Y.
var smallerY = y1 + smallerYLen;

// Draw a circle at the new point on the line.
ctx.fillStyle = "red";
ctx.moveTo(smallerX, smallerY);
ctx.arc(smallerX,smallerY,3,0,2*Math.PI);
ctx.stroke();
ctx.fill();