用js生成一个色卡,传入主题色,生成依次颜色变浅的一组色卡,帮助有需要的朋友们

如题,用js生成一个色卡,传入主题色,生成依次颜色变浅的一组色卡,帮助有需要的朋友们!
在这里插入图片描述
方法如下:记得点赞评论收藏,生活愉快!

/**
 * 输入初始颜色 "rgba(29,67,243,1)" 生成一组逐渐变浅的一组颜色
 * @param color
 */
export function generateLighterColors(color: string): string[] {
    let r: number, g: number, b: number, a: number;

    if (color.startsWith("#")) {
        color = color.slice(1);
        if (color.length === 3) {
            color = color
                .split("")
                .map((c) => c + c)
                .join("");
        }

        r = parseInt(color.substr(0, 2), 16);
        g = parseInt(color.substr(2, 2), 16);
        b = parseInt(color.substr(4, 2), 16);
    } else if (color.startsWith("rgba")) {
        const rgba = color.match(/\d+(\.\d+)?/g);
        r = parseInt(rgba![0], 10);
        g = parseInt(rgba![1], 10);
        b = parseInt(rgba![2], 10);
        a = parseFloat(rgba![3]);
    } else {
        throw new Error("Invalid color format");
    }

    const lighterColors: string[] = [];

    for (let i = 0; i < 7; i++) {
        const factor = 1 + i * 0.2; // 调整因子,用于控制颜色变浅程度
        const newR = Math.round(r * factor);
        const newG = Math.round(g * factor);
        const newB = Math.round(b * factor);

        // @ts-ignore
        const rgba = a !== undefined ? `rgba(${newR}, ${newG}, ${newB}, ${a * (1 - i * 0.15)})` : `rgba(${newR}, ${newG}, ${newB})`;
        lighterColors.push(rgba);
    }

    return lighterColors;
}

调用:

// 根据主题色生成颜色
const colorList = generateLighterColors(`rgba(29,67,243,1)`)
console.log(colorList)

你可能感兴趣的:(javascript,前端,开发语言)