css:echarts渐变色转换为css渐变色

通过一个下拉框来选择渐变类型,为了简化,我设置了三种:水平方向的渐变、垂直方向的渐变和径向渐变用,表格来配置echarts渐变色的百分比位置和颜色。

 config是表格里的数据格式如下:

offset是百分比位置,color是对应位置的颜色,new graphic前面四个参数表示渐变的方向,我这里默认是从上到下,从左到右,想要反过来的话,直接把颜色反过来就行了。

let config = ref([
  { offset: 0, color: '#e9a90a' },
  { offset: 0.5, color: '#0bcfcf' },
  { offset: 1, color: '#cc0ce6' }
])
if (tempGradualType.value === 'linearY') {
      // 垂直方向的线性渐变
      temp = new graphic.LinearGradient(
        0, 0, 0, 1, JSON.parse(JSON.stringify(config.value))
      )
    }
    else if (tempGradualType.value === 'linearX') {
      // 水平方向的线性渐变
      temp = new graphic.LinearGradient(
        0, 0, 1, 0, JSON.parse(JSON.stringify(config.value))
      )
    } else {
      // 径向渐变
      temp = new graphic.RadialGradient(
        radial.value.x, radial.value.y, radial.value.r, JSON.parse(JSON.stringify(config.value))
      )
    }

最后生成的echarts颜色是这样的,type表示线性渐变还是径向渐变,colorStops就是刚才在表格里设置的数组。

现在我们还要把echarts的渐变色格式换成css的格式,因为要做下图这样的颜色指示块。

这种颜色指示块,其实就是给一个div设置渐变色背景。 

 <div v-else style="width: 100%;height: 100%" @click="showGradualDialog(item, index)"
          :style="{ backgroundImage: getBackgroundImage(item) }">

 css里线性渐变从上到下,是to bottom,从左到右,是to right,把颜色数组像['#000','#111','#222']放进去即可,不需要设置百分比位置。径向渐变需要设置起点坐标,从echarts颜色的xy取值即可。

const getBackgroundImage = (item) => {
  const data = JSON.parse(JSON.stringify(item))
  let bgc = ''
  const colors = data.colorStops.map((config) => {
    return config.color
  }).join(',')
  if (data.type === 'linear') {
    if (data.x2 === 0 && item.y2 === 1) {
      // 从上到下:0,0,0,1
      bgc = 'linear-gradient(to bottom,' + colors + ')'
    } else if (data.x2 === 1 && data.y2 === 0) {
      // 从左到右:0,0,1,0
      bgc = 'linear-gradient(to right,' + colors + ')'
    }
  } else {
    // 径向渐变
    bgc = 'radial-gradient(circle at ' + data.x + ' ' + data.y + ',' + colors + ')'
  }
  return bgc
}

最终效果:

相关推荐

  1. el-progress变色

    2024-04-20 10:16:04       43 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-20 10:16:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-20 10:16:04       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-20 10:16:04       82 阅读
  4. Python语言-面向对象

    2024-04-20 10:16:04       91 阅读

热门阅读

  1. 如何在 Linux 和 Mac 终端命令中添加别名

    2024-04-20 10:16:04       34 阅读
  2. SpringMVC中,/和/*和/**分别表示什么

    2024-04-20 10:16:04       32 阅读
  3. rknn3588 rstp

    2024-04-20 10:16:04       35 阅读
  4. 每天学习一个Linux命令之chroot

    2024-04-20 10:16:04       34 阅读
  5. 文心一言 vs GPT-4 —— 全面横向比较

    2024-04-20 10:16:04       35 阅读
  6. php 笔记 01

    2024-04-20 10:16:04       35 阅读
  7. GateWay基本配置

    2024-04-20 10:16:04       42 阅读
  8. Linux环境部署MySQL

    2024-04-20 10:16:04       28 阅读