blog icon indicating copy to clipboard operation
blog copied to clipboard

如何实现一个色值区间(from, to)的n等分

Open zp1112 opened this issue 6 years ago • 2 comments

今天遇到一个需求是,给出两个色值假设#269f42到#2fcb53,然后进行n等分。实现这样的效果

image

起始色值和终止色值由ui给出,然后数据数量(n)不是固定的,因此需要实现颜色的n等分。

// 实现十六进制转十进制,color可以是#fff或#ffffff格式
const hexToDec = (color) => {
  if (!(/^#[0-9a-fA-F]{3,6}$/.test(color))) {
    throw new Error('color十六进制格式不正确');
  }
  color = color.replace('#', '');
  const hex = color.length == 3 ? color.replace(/(\w)/g, "$1$1,") : color.replace(/(\w{2})/g, "$1,");
  return hex.substr(0, hex.length - 1).split(',').map(row => parseInt(row, 16));
}
// 实现十进制转十六进制
const decToHex = (arr) => {
  return arr.map(row => parseInt(row, 10).toString(16)).join('');
}
// 实现等分
const divideColor = (from, to, n) => {
  const fromArr = hexToDec(from);
  const toArr = hexToDec(to);
  const gaps = [];
  const res = [];
  fromArr.forEach((row, i) => {
    gaps.push(parseInt((toArr[i] - row) / n, 10));
  })
  for (let j = 0; j < n; j++) {
    res.push(`#${decToHex(fromArr.map((row, i) => `${row + gaps[i] * j}`))}`);
  }
  return res;
}

divideColor('#269f42', '#2fcb53', 10);
// ["#269f42", "#26a343", "#27a745", "#28ac47", "#29b048", "#2ab54a", "#2bb94c", "#2cbd4d", "#2dc24f", "#2ec651"]

zp1112 avatar May 10 '18 17:05 zp1112

正则用得好6.

blackmatch avatar May 11 '18 01:05 blackmatch

666666

WoooTer avatar May 11 '18 16:05 WoooTer