1

I have a color picker, and the hue values returned are numbers between zero and 1. To create variations on the hue, I add .2 for 20%, .8 for 80% etc.

How can I keep the numbers going around the circle, so that when the number goes above 1, it subtracts the 1. How can I make this number into this number: 1.73540012511 ---> .7354

I tried using a "cents" javascript, (http://www.irt.org/script/6.htm) but this returned values greater than 1: http://jsfiddle.net/Se9Dn/

I can't use Math.min, because I want 1.2 to become .2 (not to have the colors all become red when they hit 1).

Thanks. :)


Edit: Confirming solution, with rounding added. Assuming you have an HSL color (Hue, Saturation, Luminosity) returned from Farbtastic and want to adjust Hue mathematically:

hslcolor  = (.73802938, .59832908, .948987);
colorStep = .2;
newcolor[0] = Math.round ( ((1*colorStep +hslcolor[0])%1)*10000 ) /10000;

Watch out those parenthesis are very tricky in there.

1
  • If it's greater than 1 just subtract 1 ... Commented Aug 10, 2012 at 11:59

2 Answers 2

5

You can use the modulo operator % (MDN docu).

So for adding, e.g., 0.8:

result = (result + 0.8) % 1;

EDIT

The modulo operator of JavaScript is actually more of a remainder operator.

Citing the ECMAScript spec Section 5.2:

The notation “x modulo y” (y must be finite and nonzero) computes a value k of the same sign as y (or zero) such that abs(k) < abs(y) and x−k = q × y for some integer q.

Sign up to request clarification or add additional context in comments.

4 Comments

No. That will always return an integer remainder, which is not at all what's requested here.
Whoa, you're right ... I don't understand how that makes sense, but as I noted a moment ago I haven't had a drop of coffee this morning so parts of my brain aren't working.
The code example in the answer will return NaN, since no value was set when the variable is declared above and used on the same line.
@Sirko yes I guess my concept of % got stuck shortly after I learned C 30 years ago :-)
1

You just subtract the integer:

function cent(amount) { return (+amount) - Math.floor(+amount); }

If the number can be negative, then the it depends on the semantics you want. I'll leave that as an exercise :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.