Posted By

asterfr on 09/11/09


Tagged

colorinterpolation


Versions (?)

Color Interpolation


 / Published in: JavaScript
 

Use case : interpolateColor("00EEDD","3ADECE",2,1) : interpolate the color level 1 between #00EEDD et #3ADECE on a 3 level scales (from 0 to 2).

  1. function interpolateColor(minColor,maxColor,maxDepth,depth){
  2.  
  3. function d2h(d) {return d.toString(16);}
  4. function h2d(h) {return parseInt(h,16);}
  5.  
  6. if(depth == 0){
  7. return minColor;
  8. }
  9. if(depth == maxDepth){
  10. return maxColor;
  11. }
  12.  
  13. var color = "#";
  14.  
  15. for(var i=1; i <= 6; i+=2){
  16. var minVal = new Number(h2d(minColor.substr(i,2)));
  17. var maxVal = new Number(h2d(maxColor.substr(i,2)));
  18. var nVal = minVal + (maxVal-minVal) * (depth/maxDepth);
  19. var val = d2h(Math.floor(nVal));
  20. while(val.length < 2){
  21. val = "0"+val;
  22. }
  23. color += val;
  24. }
  25. return color;
  26. }

Report this snippet  

You need to login to post a comment.