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();
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.