canvas生成临时头像

有写后台项目,右上角会有一个字母或名字截取,随机生成颜色的头像,码云也有类似的功能,记录一下,玩意哪天产品抽风了,说想要,直接复制粘贴实现;

/*
* 生成临时头像 
* nickName: 用户名
* color: 字体颜色
* size: 头像大小
*/

export class GenerateTemporaryAvatar {
    canvas: HTMLCanvasElement;
    ctx: CanvasRenderingContext2D | any;
    nickName: string;
    color: string;
    size: number;
    constructor() {
        this.canvas = document.createElement('canvas');
        this.ctx = this.canvas.getContext('2d');
        this.nickName = "无";
        this.color = '#fff';
        this.size = 50;
        
    }
    generate(nickName: string, bgcolor?: string | null, color?: string, size?: number) {
        // 钉钉bgcolor:"#0089FF"
        this.nickName = nickName || "无";
        this.color = color || '#fff';
        this.size = size || 50;
        // 设置头像大小
        const avatarSize = this.size ;
        // 设置头像内部文字大小
        const fontSize = avatarSize / 2.5;
        // 设置头像内部字体
        const fontWeight = 'normal';
        // 设置随机头像背景颜色
        const colors = [
            "#31bc9f", "#33cc70", "#4a94db", "#9b5fb6", "#34495e",
            "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50", 
            "#f1cb1e", "#e6761b", "#e7363b", "#00bcd4", "#95a5a6",
            "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"
        ];
        const avatarColor = bgcolor ? bgcolor : colors[Math.floor(Math.random() * colors.length)];
        // 初始化canvas
        const canvas = this.canvas;
        canvas.width = avatarSize;
        canvas.height = avatarSize;
        const context = this.ctx;
        // 头像背景颜色设置
        context.fillStyle = avatarColor;
        // 清除画布
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.fillRect(0, 0, canvas.width, canvas.height);
        // 头像字体颜色设置
        context.fillStyle = this.color;
        context.font = fontWeight + ' bold' + ' ' + fontSize + 'px Arial,sans-serif';
        context.textAlign = 'center';
        context.textBaseline = 'middle';

        context.fillText(nickName.slice(-2), 25, 25);
        const url = canvas.toDataURL("image/png");
        return url;
    }
};
使用
const nameToBase64 = new GenerateTemporaryAvatar();
let tmpUrl = nameToBase64.generate('YYH', "#53ACFF");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值