您当前的位置: 首页 > 

彭世瑜

暂无认证

  • 2浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Canvas绘制圆形头像

彭世瑜 发布时间:2022-01-16 09:42:04 ,浏览量:2

在这里插入图片描述 实现代码



    
        let Canvas = document.querySelector('#canvas');
        let ctx = Canvas.getContext("2d");

        // 绘制画布背景
        ctx.fillStyle = "#ccc";
        ctx.fillRect(0, 0, 500, 500);

        // 绘制圆形头像
        let avatar = new Image();
        avatar.src = 'https://api.sunweihu.com/api/sjtx/api.php?lx=c1';

        avatar.onload = (res) => {
            // console.log(res);
            console.log(avatar.height, avatar.width);
            drawCircleImage(ctx, avatar, 250, 250, 100);

            // 图像绘制完成之后继续绘制其他内容
            ctx.strokeStyle = 'red'
            ctx.strokeRect(20, 20, 460, 460);
        }

        /**
         * ctx 画布上下文
         * img 图片对象
         * (x, y)圆心坐标
         * radius 半径
         * 注意:绘制圆形头像之前,保存画笔;绘制完成后恢复
         * */
        function drawCircleImage(ctx, img, x, y, radius) {
            ctx.save();

            let size = 2 * radius;
            ctx.arc(x, y, radius, 0, 2 * Math.PI);
            ctx.clip();
            ctx.drawImage(img, x - radius, y - radius, size, size);

            ctx.restore();
        }

在线demo: https://mouday.github.io/front-end-demo/canvas/canvas-avatar.html

参考 canvas绘制圆角头像

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.0831s