封装颜色加深函数

传递一个16进制的颜色值和加深程度即可计算出加深后的值

// 颜色值加深函数
const darkenColor = (color: string, amount: number) => {
	// 去除可能存在的 # 号
	color = color.replace("#", "");
	// 将颜色值转换为RGB格式
	let r: number | string = parseInt(color.substring(0, 2), 16);
	let g: number | string = parseInt(color.substring(2, 4), 16);
	let b: number | string = parseInt(color.substring(4, 6), 16);
	// 计算加深后的颜色值
	r = Math.floor(r * (1 - amount));
	g = Math.floor(g * (1 - amount));
	b = Math.floor(b * (1 - amount));
	// 将RGB值转换回十六进制,并保证每个通道值在0到255之间
	r = (r < 0 ? 0 : r > 255 ? 255 : r).toString(16);
	g = (g < 0 ? 0 : g > 255 ? 255 : g).toString(16);
	b = (b < 0 ? 0 : b > 255 ? 255 : b).toString(16);
	// 组合成新的颜色值
	const darkenedColor = `#${r}${g}${b}`;
	return darkenedColor;
};

使用方式:

darkenColor("#3498db", 0.5)//加深百分之50

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值