过渡颜色生成器

/*
 * @Author: hope.deng
 * @Date: 2019-12-18 16:34:37
 * @LastEditors  : hope.deng
 * @LastEditTime : 2019-12-19 14:57:27
 * @Description: 获取颜色 colors 颜色范围内的 count 个 过渡颜色
 */
export default {
  getColors (count, colors) {
    const canvas = document.createElement('canvas')
    canvas.setAttribute('width', count)
    canvas.setAttribute('height', 20)
    const ctx = canvas.getContext('2d')
    const gradient = ctx.createLinearGradient(0, 0, count, 0)
    const per = 1 / (colors.length - 1)
    for (let i = 0; i < colors.length; i++) {
      gradient.addColorStop(i * per, colors[i])
    }
    ctx.fillStyle = gradient
    ctx.fillRect(0, 0, count, 1)
    const imageData = ctx.getImageData(0, 0, count, 1).data
    const cls = []
    for (let i = 0; i < imageData.length; i += 4) {
      cls.push(`rgb(${imageData[i]},${imageData[i + 1]},${imageData[i + 2]})`)
    }
    return cls
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容