根据数据获取渐变背景色

根据数据获取渐变背景色

/**
 * WFL 风场数据
 */
const LD = {
    
    
  WFL: {
    
    
    color: [
      [[124, 119, 108, 1]],
      [[80, 117, 174, 1]],
      [[69, 130, 194, 1]],
      [[64, 147, 171, 1]],
      [[80, 182, 138, 1]],
      [[82, 169, 99, 1]],
      [[106, 205, 91, 1]],
      [[158, 212, 76, 1]],
      [[218, 169, 82, 1]],
      [[217, 169, 82, 1]],
      [[210, 116, 102, 1]],
      [[178, 69, 110, 1]],
      [[142, 42, 83, 1]],
      [[91, 19, 43, 1]],
      [[49, 2, 7, 0.6]],
    ],
    data: [
      "0m/s",
      "2m/s",
      "4m/s",
      "6m/s",
      "8m/s",
      "10m/s",
      "12m/s",
      "14m/s",
      "18m/s",
      "22m/s",
      "26m/s",
      "30m/s",
      "34m/s",
      "38m/s",
      "42m/s",
    ],
    unit: "m/s",
  },
};

interface T {
    
    
  color: any[];
  data: any[];
  unit?: string;
}
/**
 * 根据数据获取对应图例背景色
 *
 * 1、得到不带单位的数组 d,
 *
 * 2、得到比传入数据小的值的数组长度 i1,
 *
 * 3、根据i1和data长度处理边界问题
 * @param {number} n 数值
 * @param {string} type 数据类型 要与文件上面定义的一致
 * @param {object} options  自行传入数据
 * @param {any} options.color 颜色
 * @param {any} options.data 图例值
 * @param {string} options.unit 单位
 * @returns 渐变背景色样式
 * @example getBackgroundColor(temp,'WFL')
 * @example getBackgroundColor(temp,'',{ color: [[[113, 129, 188, 0.0]]],data: ["0mm"],unit: "mm",})
 */
export const getBackgroundColor = (n: string | number, type: string, o?: T) => {
    
    
  if (!n) return {
    
    };
  let l: T;
  if (o) {
    
    
    l = o;
  } else {
    
    
    l = LD[type];
  }
  let d = l.data.map((e: string) => {
    
    
    let t: string | number;
    if (l.unit) {
    
    
      t = e.substring(0, e.length - l.unit.length);
    } else {
    
    
      t = e;
    }
    return t;
  });
  let i1 = d.filter((i: string) => Number(i) <= Number(n)).length;
  let i2: number;
  if (l.data.length === i1) {
    
    
    i2 = i1 - 1;
    i1 = i1 - 2;
  } else if (i1 === 0) {
    
    
    i2 = i1 + 1;
  } else {
    
    
    i2 = i1 - 1;
  }
  let c1 = l.color[i1][0] || l.color[0][0];
  let c2 = l.color[i2][0] || l.color[0][0];
  return {
    
    
    backgroundImage: `linear-gradient(to right,rgba(${
      
      c1[0]},${
      
      c1[1]},${
      
      c1[2]},${
      
      c1[2]}), rgba(${
      
      c2[0]},${
      
      c2[1]},${
      
      c2[2]},${
      
      c2[2]}))`,
  };
};

猜你喜欢

转载自blog.csdn.net/weixin_44885062/article/details/131245238