canvas绘制圆角头像

假如你想绘制的网页包括一个圆弧形的头像的canvas图片,然则头像自身是正方形的,须要的要领以下:
起首, 拿到头像在画布上的坐标和宽高:(详细怎样猎取不在此做详细引见)

let {avatarX, avatarY, avatarW, avatarH} = {20, 20, 80, 80};

然后 只须要挪用以下函数即可:

let Canvas = document.createElement('canvas');
let ctx = Canvas.getContext("2d");
let avatar = new Image();
avatar.src = '../src/xx.png';
avatar.onload = (scaleBy = 2) => {
   circleImg(ctx, avatar, avatarX * scaleBy, avatarY * scaleBy, avatarW * scaleBy / 2);
}

// r: 半径
function circleImg(ctx, img, x, y, r) {
    ctx.save();
    var d =2 * r;
    var cx = x + r;
    var cy = y + r;
    ctx.arc(cx, cy, r, 0, 2 * Math.PI);
    ctx.clip();
    ctx.drawImage(img, x, y, d, d);
    ctx.restore();
} 
    原文作者:不会飞的Porco
    原文地址: https://segmentfault.com/a/1190000017927730
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞