关于element-ui换肤功能源码中的getThemeCluster函数

getThemeCluster(theme) {
      const tintColor = (color, tint) => {
        let red = parseInt(color.slice(0, 2), 16)
        let green = parseInt(color.slice(2, 4), 16)
        let blue = parseInt(color.slice(4, 6), 16)
        if (tint === 0) { // when primary color is in its rgb space
          return [red, green, blue].join(',')
        } else {
          red += Math.round(tint * (255 - red))
          green += Math.round(tint * (255 - green))
          blue += Math.round(tint * (255 - blue))
          red = red.toString(16)
          green = green.toString(16)
          blue = blue.toString(16)
          return `#${red}${green}${blue}`
        }
      }
      const shadeColor = (color, shade) => {
        let red = parseInt(color.slice(0, 2), 16)
        let green = parseInt(color.slice(2, 4), 16)
        let blue = parseInt(color.slice(4, 6), 16)
        red = Math.round((1 - shade) * red)
        green = Math.round((1 - shade) * green)
        blue = Math.round((1 - shade) * blue)
        red = red.toString(16)
        green = green.toString(16)
        blue = blue.toString(16)
        return `#${red}${green}${blue}`
      }
      const clusters = [theme]
      for (let i = 0; i <= 9; i++) {
        clusters.push(tintColor(theme, Number((i / 10).toFixed(2))))
      }
      clusters.push(shadeColor(theme, 0.1))
      return clusters
    }

源码地址
此函数的参数theme是一个色值,比如说409EFF。然后函数一进来定义了tintColor与shadeColor两个函数,然后for循环了10次依次执行clusters.push(tintColor(theme, Number((i / 10).toFixed(2)))),最后再执行clusters.push(shadeColor(theme, 0.1)),return clusters。从断点调试的结果来看,最后生成的clusters是包含一系列色值的数组。

我不明白tintColor与shadeColor到底做了什么事,生成的那一堆色值有什么联系。传入的tint与shade参数又是什么意思,为什么要循环10次。

阅读 3.9k
2 个回答

假如 theme 是 '红色'
有些按钮是根据主题色计算出来的 '浅红色'
tint函数就是计算出来这个浅红色的方法
大概是下面这样的
红色 * 透明度(0.2) = 浅红色
循环10次就是计算出是个不同程度的浅红色
建议看一下less 文档

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题