js 生成随机颜色

js yekong 344℃

数据可视化大屏项目开发工程中,echarts图表需要实现配置一批颜色,但是后端返回的数据可能会超过前端配置的颜色,这时候我们就需要生成一批随机颜色了。

在JavaScript中,你可以使用以下方法生成随机颜色:

方法一:生成随机的RGB颜色值

function getRandomRGB() {
  var r = Math.floor(Math.random() * 256); // 随机生成 0 到 255 之间的整数
  var g = Math.floor(Math.random() * 256);
  var b = Math.floor(Math.random() * 256);
  var rgb = 'rgb(' + r + ',' + g + ',' + b + ')';
  return rgb;
}

var randomColor = getRandomRGB();
console.log(randomColor);

方法二:生成随机的十六进制颜色值

function getRandomHexColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

var randomColor = getRandomHexColor();
console.log(randomColor);

在上述方法中,getRandomRGB()函数生成一个随机的RGB颜色值,而getRandomHexColor()函数生成一个随机的十六进制颜色值。

你可以根据需要选择使用RGB颜色值还是十六进制颜色值。这些方法将生成一个随机的颜色,你可以将其应用于需要随机颜色的地方,如文本、背景色、边框等。

使用

list2() {
  var colorList = [
    {
      name: '产业帮扶金',
      value: 489,
      color1: 'rgba(253, 168, 62, 1)',
      color2: 'rgba(254, 217, 82, 1)',
      checked: true
    },
    {
      name: '就业帮扶金',
      value: 489,
      color1: 'rgba(8, 170, 135, 1)',
      color2: 'rgba(14, 224, 159, 1)',
      checked: true
    },
    {
      name: '金融帮扶金',
      value: 789,
      color1: 'rgba(15, 234, 234, 1)',
      color2: 'rgba(11, 155, 159, 1)',
      checked: true
    },
    {
      name: '健康帮扶金',
      value: 236,
      color1: 'rgba(8, 124, 255, 1)',
      color2: 'rgba(25, 137, 251, 1)',
      checked: true
    },
    {
      name: '教育帮扶金',
      value: 125,
      color1: 'rgba(221, 234, 15, 1)',
      color2: 'rgba(140, 217, 18, 1)',
      checked: true
    },
    {
      name: '兜底帮扶金',
      value: 456,
      color1: 'rgba(234, 82, 15, 1)',
      color2: 'rgba(248, 101, 20, 1)',
      checked: true
    },
    {
      name: '其他金额',
      value: 452,
      color1: 'rgba(247, 18, 56, 1)',
      color2: 'rgba(248, 20, 111, 1)',
      checked: true
    }, {
      name: '公益帮扶金',
      value: 723,
      color1: 'rgba(94, 18, 247, 1)',
      color2: 'rgba(154, 20, 248, 1)',
      checked: true
    }]
  var list = []
  this.list.forEach((type, index) => {
    list.push({
      name: type.name,
      value: type.value,
      color1: colorList[index]?.color1 ? colorList[index]?.color1 : this.getRandomHexColor(),
      color2: colorList[index]?.color2 ? colorList[index]?.color2 : this.getRandomHexColor(),
      checked: true
    })
  });
  return list
}
喜欢 (0)