title: How to interpolate hue values in HSV colour space?
body: <p>I'm trying to interpolate between two colours in HSV colour space to produce a smooth colour gradient.</p>
  
  <p>I'm using a linear interpolation, eg:</p>
  
  <pre><code>h = (1 - p) * h1 + p * h2
  s = (1 - p) * s1 + p * s2
  v = (1 - p) * v1 + p * v2
  </code></pre>
  
  <p>(where p is the percentage, and h1, h2, s1, s2, v1, v2 are the hue, saturation and value components of the two colours)</p>
  
  <p>This produces a good result for s and v but not for h. As the hue component is an angle, the calculation needs to work out the shortest distance between h1 and h2 and then do the interpolation in the right direction (either clockwise or anti-clockwise).</p>
  
  <p>What formula or algorithm should I use?  </p>
  
  <hr>
  
  <p>EDIT: By following Jack's suggestions I modified my JavaScript gradient function and it works well. For anyone interested, here's what I ended up with:</p>
  
  <pre><code>// create gradient from yellow to red to black with 100 steps
  var gradient = hsbGradient(100, [{h:0.14, s:0.5, b:1}, {h:0, s:1, b:1}, {h:0, s:1, b:0}]); 
  
  function hsbGradient(steps, colours) {
    var parts = colours.length - 1;
    var gradient = new Array(steps);
    var gradientIndex = 0;
    var partSteps = Math.floor(steps / parts);
    var remainder = steps - (partSteps * parts);
    for (var col = 0; col &lt; parts; col++) {
      // get colours
      var c1 = colours[col], 
          c2 = colours[col + 1];
      // determine clockwise and counter-clockwise distance between hues
      var distCCW = (c1.h &gt;= c2.h) ? c1.h - c2.h : 1 + c1.h - c2.h;
          distCW = (c1.h &gt;= c2.h) ? 1 + c2.h - c1.h : c2.h - c1.h;
       // ensure we get the right number of steps by adding remainder to final part
      if (col == parts - 1) partSteps += remainder; 
      // make gradient for this part
      for (var step = 0; step &lt; partSteps; step ++) {
        var p = step / partSteps;
        // interpolate h, s, b
        var h = (distCW &lt;= distCCW) ? c1.h + (distCW * p) : c1.h - (distCCW * p);
        if (h &lt; 0) h = 1 + h;
        if (h &gt; 1) h = h - 1;
        var s = (1 - p) * c1.s + p * c2.s;
        var b = (1 - p) * c1.b + p * c2.b;
        // add to gradient array
        gradient[gradientIndex] = {h:h, s:s, b:b};
        gradientIndex ++;
      }
    }
    return gradient;
  }
  </code></pre>