Get the distance between two points in the canvas

I have a canvas drawing tab and want the lineWidth to be based on the distance between the last two updates to the mousemove coordinates. I will translate the distance to the width itself, I just need to know how to get the distance between these points (I already have the coordinates of these points).

+71
javascript canvas
Jan 04 '14 at 4:37
source share
5 answers

You can do this using the Pythagorean theorem

If you have two points (x1, y1) and (x2, y2), then you can calculate the difference in x and the difference in y, let's call them a and b.

enter image description here

var a = x1 - x2; var b = y1 - y2; var c = Math.sqrt( a*a + b*b ); // c is the distance 
+149
Jan 04 '14 at 4:41
source share

Please note that Math.hypot is part of the ES2015 standard. There's also a good polyfill in

+97
Nov 16 '15 at 19:29
source share

http://en.wikipedia.org/wiki/Euclidean_distance

If you have coordinates, use the formula to calculate the distance:

 var dist = Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2) ); 

If your platform supports ** , you can use this:

 const dist = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2); 
+20
Jan 04 '14 at 4:41
source share

The distance between the two x and y coordinates! x1 and y1 - the first point / position, x2 and y2 - the second point / position!

 function diff (num1, num2) { if (num1 > num2) { return (num1 - num2); } else { return (num2 - num1); } }; function dist (x1, y1, x2, y2) { var deltaX = diff(x1, x2); var deltaY = diff(y1, y2); var dist = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); return (dist); }; 
+1
Jun 15 '17 at 15:49
source share

I try to use this calculation a lot in the things I do, so I like to add it to the Math object:

 Math.dist=function(x1,y1,x2,y2){ if(!x2) x2=0; if(!y2) y2=0; return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); } Math.dist(0,0, 3,4); //the output will be 5 Math.dist(1,1, 4,5); //the output will be 5 Math.dist(3,4); //the output will be 5 

Update:

this approach is especially pleasing when you find yourself in situations similar to this (I often do this):

 varName.dist=Math.sqrt( ( (varName.paramX-varX)/2-cx )*( (varName.paramX-varX)/2-cx ) + ( (varName.paramY-varY)/2-cy )*( (varName.paramY-varY)/2-cy ) ); 

this terrible thing becomes much more manageable:

 varName.dist=Math.dist((varName.paramX-varX)/2, (varName.paramY-varY)/2, cx, cy); 
0
Oct 27 '15 at 3:54 on
source share



All Articles