Skip to content

Commit

Permalink
fix(calcAngleBetweenVectors): use atan2 instead of dot product
Browse files Browse the repository at this point in the history
  • Loading branch information
Luiz Zappa committed Jul 27, 2022
1 parent 7f01868 commit 37e4fac
Showing 1 changed file with 7 additions and 20 deletions.
27 changes: 7 additions & 20 deletions src/util/misc.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,6 @@
* @namespace fabric.util
*/
fabric.util = {
/**
* Calculate the arccosine of an angle, avoiding values outside [-1, 1]
* @static
* @memberOf fabric.util
* @param {Number} value the value of the cosine
* @return {Number}
*/
acos: function(value) {
var adjustedValue= Math.max(-1, Math.min(value, 1));
return Math.acos(adjustedValue);
},

/**
* Calculate the cos of an angle, avoiding returning floats for known results
* @static
Expand Down Expand Up @@ -169,17 +157,18 @@
},

/**
* Calculates angle between 2 vectors using dot product
* Calculates angle between 2 vectors using atan2
* @static
* @memberOf fabric.util
* @param {Point} a
* @param {Point} b
* @returns the angle in radian between the vectors
*/
calcAngleBetweenVectors: function (a, b) {
return fabric.util.acos(
(a.x * b.x + a.y * b.y) / (Math.sqrt(a.x * a.x + a.y * a.y) * Math.sqrt(b.x * b.x + b.y * b.y))
);
var dot = a.x * b.x + a.y * b.y,
det = a.x * b.y - a.y * b.x;

return Math.atan2(det, dot);
},

/**
Expand All @@ -203,12 +192,10 @@
getBisector: function (A, B, C) {
var AB = fabric.util.createVector(A, B), AC = fabric.util.createVector(A, C);
var alpha = fabric.util.calcAngleBetweenVectors(AB, AC);
// check if alpha is relative to AB->BC
var ro = fabric.util.calcAngleBetweenVectors(fabric.util.rotateVector(AB, alpha), AC);
var phi = alpha * (Math.abs(ro) <= 1e-7 ? 1 : -1) / 2;
var phi = alpha / 2;
return {
vector: fabric.util.getHatVector(fabric.util.rotateVector(AB, phi)),
angle: alpha
angle: Math.abs(alpha)
};
},

Expand Down

0 comments on commit 37e4fac

Please sign in to comment.