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");

你可能感兴趣的:(javascript,前端)