Anagmate - 3 months ago 37

Javascript Question

I have canvas drawing tab and want lineWidth to be based on distance between two last mousemove coordinate updates. I will make translation of distance to width myself, I just need to know how to get distance between those points (I already have coordinates of those pointes).

Answer

You can do it with pythagoras theorem

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

```
var a = x1 - x2
var b = y1 - y2
var c = Math.sqrt( a*a + b*b );
// c is the distance
```

a shorter way to write the above would be

```
var d = Math.sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) );
```

**Update**

...thanks to Jonas for this slightly *minimized* way: (caution - this will change the values of your original variables)

```
var d = Math.sqrt( (x2-=x1)*x2 + (y2-=y1)*y2 );
```