js 根据姓氏生成头像

2023-03-21  本文已影响0人  littlesunn
    function createImgUrlForName(name = '孙晓敏', backgroundColor = "yellow", fontColor = "#000") {
        let canvasEle = document.createElement("canvas");
        let ctx = canvasEle.getContext('2d');
        canvasEle.width = 200;
        canvasEle.height = 200;
        let cWidth = ctx.canvas.width;
        let cHeight = ctx.canvas.height;
        ctx.fillStyle = backgroundColor;
        ctx.fillRect(0, 0, cWidth, cHeight)
        let fontSize = canvasEle.width * 0.8;
        ctx.font = fontSize + 'px 黑体';
        ctx.fillStyle = fontColor;
        ctx.fillText(name[0], cWidth / 2 - fontSize / 2, cHeight / 2 + fontSize / 3);
        var tempSrc = canvasEle.toDataURL("image/png");
        return tempSrc;
    }

返回的是base64的图片地址,直接放到src就好啦

image.png image.png
上一篇下一篇

猜你喜欢

热点阅读