html5-canvasfabricjsfabricjs2

Calculate hue rotation in fabric js


How to we calculate rotation parameter value(-1 to 1) in Hue Rotation Filter in fabricjs from normal hue degree value(0-360)?

How does fabricjs calculate the rotation value in the Hue Rotation filter?


Solution

  • The rotation is from -180 to 180, just for simmetry with other filters like contrast and brightness that move from -1 to 1.

    When fabricjs calculate the rotation multiply the value of rotation for Math.PI so it moves from -1 radian to 1 radian, making a full rotation of 2 radians that equal to 360 degree.

    Since the hue rotation matrix is built just with sin and cos that are periodic function of the angle in radians, you do not have to worry about the limit. If you want to set rotation to 2 is fine, you will get the same result as 0. rotation of 3 will give the result of and so on.

    calculateMatrix: function() {
      var rad = this.rotation * Math.PI, cos = Math.cos(rad), sin = Math.sin(rad),
          aThird = 1 / 3, aThirdSqtSin = Math.sqrt(aThird) * sin, OneMinusCos = 1 - cos;
      this.matrix = [
        1, 0, 0, 0, 0,
        0, 1, 0, 0, 0,
        0, 0, 1, 0, 0,
        0, 0, 0, 1, 0
      ];
      this.matrix[0] = cos + OneMinusCos / 3;
      this.matrix[1] = aThird * OneMinusCos - aThirdSqtSin;
      this.matrix[2] = aThird * OneMinusCos + aThirdSqtSin;
      this.matrix[5] = aThird * OneMinusCos + aThirdSqtSin;
      this.matrix[6] = cos + aThird * OneMinusCos;
      this.matrix[7] = aThird * OneMinusCos - aThirdSqtSin;
      this.matrix[10] = aThird * OneMinusCos - aThirdSqtSin;
      this.matrix[11] = aThird * OneMinusCos + aThirdSqtSin;
      this.matrix[12] = cos + aThird * OneMinusCos;
    },
    

    so

    filter.rotation = angleInDegree / Math.PI
    

    Should work