vue3仿飞书头像,根据不同名称生成不同的头像背景色

效果展示:

传递三个参数:
  • name:要显示的名称;
  • size:头像的大小;
  • cutNum:分割当前名称的最后几位数;
代码如下:
<template>
	<div
		:style="{
			color: '#fff',
			borderRadius: '50%',
			width: size + 'px',
			height: size + 'px',
			display: 'block',
			textAlign: 'center',
			lineHeight: size + 'px',
			fontSize: size * 0.4 + 'px',
			background: color(name)
		}"
	>
		{{ name.slice(-cutNum) }}
	</div>
</template>

<script lang="ts" setup>
defineProps({
	name: {
		type: String,
		default: ""
	},
	size: {
		type: Number,
		default: 16
	},
	cutNum: {
		type: Number,
		default: 1
	}
});

const color = (name: string) => {
	if (name) {
		let num = "";
		for (let i = 0; i < name.length; i++) {
			num += name[i].charCodeAt(0).toString();
		}
		const r = Math.min(100 + (parseInt(num.slice(0, 2), 10) % 55), 255);
		const g = Math.min(100 + (parseInt(num.slice(2, 4), 10) % 55), 255);
		const b = Math.min(100 + (parseInt(num.slice(4, 6), 10) % 55), 255);
		return `rgb(${r}, ${g}, ${b})`;
	} else {
		return "rgb(125, 125, 125)";
	}
};
</script>
使用代码如下:
<AuthorImage name="铁甲小宝" :size="74" :cut-num="2"></AuthorImage>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值