计算渐变色每一步的色值

计算渐变色每一步的色值 代码

//定义渐变色的起始颜色和终止颜色
let num1 = "#e52e2e";
let num2 = "#fbc918";
//定义将颜色拆分为多少份
let steps = 50
//定义不透明度
let gamma = 1
//将HEX色值转换为RGB色值
 let 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);
            }
          );
    };

    let pad = function (s) {
      return s.length === 1 ? "0" + s : s;
    };

    let gradientColors = function (start, end, steps, gamma) {
      let i,
        j,
        ms,
        me,
        output = [],
        so = [];
      gamma = gamma || 1;
      let 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;
    };
//打印结果
console.log(gradientColors(num1 , num2 , steps , gamma))

打印结果图片


1646281228871.jpg

打印结果为数组,可以根据自己的需求来取具体的色值

你可能感兴趣的:(计算渐变色每一步的色值)