js实现css的颜色平滑过渡代码

class ColorTransformer {
    _step;
    beginColor;
    endColor;
    colorTransforms;
    constructor(beginColor, endColor,_step=100) {
        this.beginColor = this.hexToRgb(beginColor.toLocaleLowerCase());
        this.endColor = this.hexToRgb(endColor.toLocaleLowerCase());
        this._step = _step;
        this.colorTransforms = this.createColorTransformList(this.beginColor,this.endColor,this._step);
    }
    /** 10进制转16进制 */
    #tenToSixteen(color_ten) {
        return Number(color).toString(16);
    }
    /** 16进制转10进制 */
    #sixteenToTen(color_sixteen) {
        return Number.parseInt(color_sixteen, 16)
    }
    /** 是否rgb格式 */
    #isRGB(rgb) {
        if(/^#[a-f|A-F|0-9]{6}$/.test(rgb)) return false;
        let res = true;
        if (typeof rgb !== 'string') return false;
        rgb = rgb.replace(/^rgb\(|\)$/g, '').split(',')
        rgb.forEach(item => {
            if (item < 0 || item > 255) res = false;
        })
        return res
    }
    /** rgb转换成数组 */
    #rgbToArr(rgb) {
        return rgb.replace(/^rgb\(|\)$/g, '').split(',').map(item => Number.parseInt(item))
    }
    /** rgb转hex */
    rgbToHex(rgb) {
        if (/^#[a-f|A-F|0-9]{6}$/.test(rgb)) return rgb;
        if (typeof rgb === "string") rgb = this.#rgbToArr(rgb);
        const [R, G, B] = rgb;
        const RR = this.#tenToSixteen(R), GG = this.#tenToSixteen(G), BB = this.#tenToSixteen(B);
        return `#${RR}${GG}${BB}`
    }
    /** hex转rgb */
    hexToRgb(hex) {
        if (this.#isRGB(hex)) return hex;
        hex = hex.replace('#', '');
        const RR = hex.slice(0, 2), GG = hex.slice(2, 4), BB = hex.slice(4);
        const R = this.#sixteenToTen(RR), G = this.#sixteenToTen(GG), B = this.#sixteenToTen(BB);
        return `rgb(${R},${G},${B})`
    }
    /** 获取颜色转换平滑数组 */
    createColorTransformList(beginColor, endColor, step) {
        const [bR, bG, bB] = this.#rgbToArr(beginColor), [eR, eG, eB] = this.#rgbToArr(endColor);
        const rR = (eR - bR) / step, rG = (eG - bG) / step, rB = (eB - bB) / step;
        const colorStepList = [];
        for (let i = 0; i < step; i++) {
            colorStepList.push(`rgb(${Number.parseInt(rR * i + bR)},${Number.parseInt(rG * i + bG)},${Number.parseInt(rB * i + bB)})`)
        }
        colorStepList.pop()
        return [...colorStepList,this.endColor] 
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值