简体   繁体   中英

Changing color of image in fabric.js

Recently I started exploring fabric.js. I want to change the color of an image by selecting a color from color picker.

I started by this example . Exploring the documentation of fabric.js I deduced (I might be wrong) that fabric uses the HSL color model. The problem is everywhere I search, the range of hue is given between 0 to 360 degrees but the HueRotation filter in fabric expects values to be between -1 to 1. In order to solve this I calculated sin of hue to bring it between -1 and 1 but that changes the colour all together.

It would be great if somebody points out what I am missing. I am using this code to convert HEX to HSL. The only difference is I calculate sin of hue by Math.sin(h * Math.PI/180) to get it into range of -1 to 1.

If this library expects a normalized range equivalent to [-180º, 180º] or [-π, π], you can't resolve it with sine or cosine. Both functions can give the same result for different angles (sin(45) == sin(135)) while those angles represent different hues (yellow and lime green).

You can convert your input to [-180º, 180º] range first:

hue = hue % 360; //handle inputs greater than 360 degrees
let displacedHue = (hue > 180) ? hue - 360 : hue

Then you normalize it to [-1, 1]:

let normalizedHue = displacedHue/180

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM