1.需要獲取用戶(hù)信息,拿到用戶(hù)頭像圖片
wx.getUserProfile({
desc: '用于生成海報(bào)', // 聲明獲取用戶(hù)個(gè)人信息后的用途,后續(xù)會(huì)展示在彈窗中,請(qǐng)謹(jǐn)慎填寫(xiě)
success: (res) => {
wx.downloadFile({
url: res.userInfo.avatarUrl,
success (res) {
if (res.statusCode === 200) {
this.setData({
file_avatar:res.tempFilePath //拿到圖片本地地址
})
}
}
})
}
})
2.實(shí)例化一個(gè)canvas對(duì)象,繪制出圓形并將頭像固定到圓形中心位置
let ctx = wx.createCanvasContext('myCanvas', this)
this.circleAvatar(ctx, this.data.file_avatar, rpx2px(150),rpx2px(150),25);
circleAvatar(ctx, img, x, y, r){
// 如果在繪制圖片之后還有需要繪制別的元素,需啟動(dòng) save() 、restore() 方法,否則 clip() 方法會(huì)
// 導(dǎo)致之后元素都不會(huì)被渲染出來(lái)
// save():保存當(dāng)前 Canvas 畫(huà)布狀態(tài)
// restore():恢復(fù)到保存時(shí)的狀態(tài)
// ctx:實(shí)例化canvas對(duì)象
// img:圖片地址
// x:圓形中心點(diǎn)x坐標(biāo)
// y:圓形中心點(diǎn)y坐標(biāo)
// r:圓形半徑
ctx.save()
let d = r * 2;
let cx = x - r;
let cy = y - r;
ctx.arc(x, y, r, 0, 2 * Math.PI);
ctx.strokeStyle = '#fff'; // 設(shè)置繪制圓形邊框的顏色
ctx.stroke(); // 繪制出圓形,默認(rèn)為黑色,可通過(guò) ctx.strokeStyle = '#FFFFFF',設(shè)置想要的顏色
ctx.clip();
ctx.drawImage(img, cx, cy, d, d);
ctx.restore();
},
3.實(shí)現(xiàn)效果
?
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-611274.html文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-611274.html
?
到了這里,關(guān)于微信小程序?qū)崿F(xiàn)canvas畫(huà)圓形微信頭像的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!