小程序中,canvas绘制图片,可使用drawImage方法,但是绘制网络图片时,在手机端不会显示,需要先将网络图片下载到本地,然后用图片的本地路径绘制。如下伪代码:
function downLoadImg(netUrl, storageKeyUrl) {
wx.getImageInfo({
src: netUrl, //请求的网络图片路径
success: function (res) {
//请求成功后将会生成一个本地路径即res.path,然后将该路径缓存到storageKeyUrl关键字中
wx.setStorage({
key: storageKeyUrl,
data: res.path,
});
}
})
}
downLoadImg(参数一,参数二)//调用如上方法
var headUrl = wx.getStorageSync(storageKeyUrl); //下面用canvas绘制头像
const ctx = wx.createCanvasContext('myCanvas');
var wxSys = wx.getSystemInfoSync();
var screenScale = wxSys.screenWidth * 2 / 750;
ctx.save(); // 保存当前ctx的状态
ctx.arc(screenScale * 182, screenScale * 355, screenScale * 22, 0, 2 * Math.PI, false);
ctx.strokeStyle = '#e3e7e8'; ctx.stroke(); ctx.clip(); //裁剪上面的圆形
if (typeof (headUrl) != 'undefined' && headUrl != '') {
ctx.drawImage(headUrl, screenScale * 160, screenScale * 333, screenScale * 44, screenScale * 44); // 在刚刚裁剪的园上画图
}
ctx.restore(); // 还原状态