在canvas画布中绘制圆形头像居中显示是比较常见的,直接上代码:
假设已经设置好了canvas的宽高;
// 先封装一个请求图片的方法。
methods: {
getNetworkImage(url) {
return new Promise((resolve,reject) => {
uni.downloadFile({
url,
success: (e) => {
const p = e.tempFilePath
if (p.indexOf('json') > -1) {
reject(p)
return false
}
resolve(p)
},
fail: (r) => {
reject(r)
}
})
})
},
}
// 绘制头像
const drawAvatar = (avatarUrl) => {
const avatarWidth = ctx.width * 0.15
const avatarLeft = (ctx.width - avatarWidth) / 2
const avatarTop = ctx.height * 0.4
ctx.save()
ctx.beginPath()
ctx.arc(avatarLeft + avatarWidth / 2, avatarTop, avatarWidth / 2, 0, Math.PI * 2, false)
ctx.fillStyle="#f3c227"
ctx.fill()
ctx.clip()
ctx.drawImage(avatarUrl, avatarLeft, avatarTop - avatarWidth / 2, avatarWidth, avatarWidth)
ctx.restore()
}
// 调用,这里请求图片try catch比较保险
let avatarPath = ''
try {
avatarPath = await this.getNetworkImage(this.userData.headimgurl)
} catch(e) {
avatarPath = '/static/img/default_avatar.png'
}
drawAvatar(avatarPath)