rileyjshaw / sweep

:rainbow: A JavaScript library for smooth color transitions
http://rileyjshaw.com/sweep/
MIT License
445 stars 33 forks source link

Add support for range changes in addition to time based changes #1

Closed roryprimrose closed 9 years ago

roryprimrose commented 9 years ago

I really want to use this library but my scenario is based on a range with a defined point in the range rather than based on a time transition between two colours.

I am using rangeslider.js to display a slider for a range input field. I want to use this library to calculate the colour at a specific point between two colours. For example, the background of the slider can start with a background colour of green. Sliding between 0% and 75% of the range will gradually transition from green to orange. Sliding between 75% and 100% will gradually transition from orange to red.

For this to work, the transition between colours is not based on a percentage/ratio value between two colours. It would be awesome if I could have my JavaScript make a call to sweep to get the new colour based of either a percentage or a ratio between points.

I'm thinking something like

var transitionColor = sweep(fromColor, toColor, percentage);
// or
var transitionColor = sweep(fromColor, toColor, min, max, current);

By percentage is nice where the range is a transition between 0-100% and only two colours are involved. By range and point is better where multiple stages are involved (like 0-75 with a current value of 35 between two colours).

rileyjshaw commented 9 years ago

Hi @roryprimrose, sorry for the delay.

I'm not sure if you need sweep for this problem.

I've pulled the color conversion code into a a standalone file, convert.js, so you can use that to get things into HSL format. HSL is defined as the triplet {[0, 360], [0%, 100%], [0%, 100%]}. Once you're there, move linearly between each component of the triplet based on your slider's value.

For example:

Starting color: green => hsl(120, 1, 0.25) Ending color: red => hsl(0, 1, 0.5) Difference: hsl(0 - 120, 1 - 1, 0.5 - 0.25) = hsl(-120, 0, 0.25)

You'll want to multiply your slider's value by the difference triplet and add that to your starting color. For example, if you're looking for the midpoint (50%) between green and red:

hsl(120 + 50% * -120, 1 + 50% * 0, 0.25 + 50% * 0.25) = hsl(60, 1, 0.375)

Sorry again for the delay. Let me know if you have any questions!