若是你想繪製的網頁包含一個圓弧形的頭像的canvas圖片,可是頭像自己是正方形的,須要的方法以下:
首先, 拿到頭像在畫布上的座標和寬高:(具體怎麼獲取不在此作具體介紹)html
使用canvas繪製圓弧動畫canvas
let {avatarX, avatarY, avatarW, avatarH} = {20, 20, 80, 80};
而後 只須要調用如下函數便可:segmentfault
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(); }