title: How to use SVG gradients to display varying colors relative to the size of the colored region
body: <p>I'm using SVG and D3 to create bar graphs and have a question concerning how to color them. I've searched many questions on this site and others and haven't yet found anyone with the same issue.</p>
  
  <p>I would like each bar to start at the bottom with one color, (yellow, e.g.) and, as the bar gets taller, progressively mix in more of the second color, (red, e.g.), so that the bars at their maximum potential height would be only the second color. In this example, the tops of the bars that are half their potential height would be orange.</p>
  
  <p>I was able to write a function to produce, for a bar of any given height, a unique linear gradient that would color the bars as desired.</p>
  
  <p>However, since this graph is dynamic and the heights of the bars may change many times per second as the data is refreshed, creating and applying a new gradient each time and for each bar is definitely not efficient and could result in serious lag in refreshing the bars. (I admit I haven't actually tried this with anything other than a static test case, so I could be wrong about that last assumption.)</p>
  
  <p>Using a static gradient of course yields something like this, where the colors are mixed according to the height of the bar, not the height of the region:</p>
  
  <p><img src="https://i.stack.imgur.com/Boolt.png" alt="Using static gradient"></p>
  
  <p>In my desired scenario, however, the smaller bars should have very little red or dark blue respectively.</p>
  
  <p><strong>My question, finally, is this: is there a way to</strong> </p>
  
  <ol>
  <li>create a single gradient that is applied to the SVG region itself (<em>easy</em>) </li>
  <li>have said gradient masked somehow (<em>easy</em>)</li>
  <li>then selectively unmasked underneath the rectangles representing the bars of the graph? (<em>???</em>)</li>
  </ol>
  
  <p>Or, is there some other technique I'm overlooking?</p>
  
  <p>Thanks</p>