js 計算兩個顏色之間的漸變色值 10個色值


https://www.zhihu.com/question/38869928

 

隨手寫的,輕噴

Changelog:

    • 應評論區要求支持 #000 這樣的三位 hex color
    • 應評論區要求支持 gamma correction。
作者:「已注銷」
鏈接:https://www.zhihu.com/question/38869928/answer/78527903
來源:知乎
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。

// convert #hex notation to rgb array
var parseColor = function (hexStr) {
  return hexStr.length === 4 ? hexStr.substr(1).split('').map(function (s) { return 0x11 * parseInt(s, 16); }) : [hexStr.substr(1, 2), hexStr.substr(3, 2), hexStr.substr(5, 2)].map(function (s) { return parseInt(s, 16); })
};

// zero-pad 1 digit to 2
var pad = function (s) {
  return (s.length === 1) ? '0' + s : s;
};

var gradientColors = function (start, end, steps, gamma) {
  var i, j, ms, me, output = [], so = [];
  gamma = gamma || 1;
  var normalize = function (channel) {
    return Math.pow(channel / 255, gamma);
  };
  start = parseColor(start).map(normalize);
  end = parseColor(end).map(normalize);
  for (i = 0; i < steps; i++) {
    ms = i / (steps - 1);
    me = 1 - ms;
    for (j = 0; j < 3; j++) {
      so[j] = pad(Math.round(Math.pow(start[j] * me + end[j] * ms, 1 / gamma) * 255).toString(16));
    }
    output.push('#' + so.join(''));
  }
  return output;
};

// try if it works
console.log(gradientColors('#00ff00', '#ff0000', 100));

// 泥萌的新需求
console.log(gradientColors('#000', '#fff', 100, 2.2));

 

 

另canvas做法

http://blog.sina.com.cn/s/blog_a1a495090102vqms.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM