canvas画出来的图像在iphone5上保存为空图片
发布于 6 年前 作者 dxue 12567 次浏览 来自 问答

createShare: function () {

let that = this;

let unit = that.data.screenWidth / 375;

let context = wx.createCanvasContext(‘canvas’, this);

that.setData({

‘canvasHidden’: false

});

wx.downloadFile({

url: app.globalData.imageUrl + ‘/inviteFriend.png’,

success: function (res) {

console.log(res);

that.setData({

‘inviteFriend’: res.tempFilePath

})

console.log(parseInt(that.data.screenWidth));

if (parseInt(that.data.screenWidth) < 375 ){

context.drawImage(that.data.inviteFriend, 0, 0, 320 * parseInt(unit), 530 * parseInt(unit));//背景  

}else{

context.drawImage(that.data.inviteFriend, 0, 0, 375 * parseInt(unit), 620 * parseInt(unit));//背景

}

context.setFontSize(36 * parseInt(unit));

context.setFillStyle(’#02C07B’);

context.fillText(that.data.inviteCode + ‘’, 124 * parseInt(unit), 195 * parseInt(unit));

context.setFontSize(14 * parseInt(unit));

context.setFillStyle(‘rgb(102,102,102)’);

context.fillText(‘我是’ + app.globalData.userInfo.nickName, 50 * parseInt(unit), 251 * parseInt(unit));

context.fillText(‘邀请您’, 50 * parseInt(unit), 271 * parseInt(unit));

context.fillText(‘我的邀请次数有限,赶快加入哦~’, 50 * parseInt(unit), 291 * parseInt(unit));

//保存图片

context.draw(false,function () {

wx.canvasToTempFilePath({

canvasId: ‘canvas’,

success : function (res) {

if (!res.tempFilePath) {

wx.showToast({

title: ‘图片绘制中’,

icon:‘none’

})

}

console.log(that.data.shareImgPath)

wx.saveImageToPhotosAlbum({

filePath: res.tempFilePath,

success: (res) => {

console.log(res)

wx.hideLoading();

that.setData({

canvasHidden: true

})

wx.showToast({

title: ‘图片保存成功’,

icon: ‘success’

});

},

fail: (err) => {

console.log(err)

wx.hideLoading();

that.setData({

canvasHidden: true

})

wx.showToast({

title: ‘图片保存失败’,

icon: ‘none’

})

}

})

},

fail : function () {

wx.showToast({

title: ‘图片绘制失败’,

icon: ‘none’

})

}

}, this)

})

}

})

// console.log(that.data.imageUrl + ‘/inviteFriend.svg’);

}

请各位大神看看是不是我的代码出问题了。

再说一下 我在其他手机上调试都是可以保存的(正常运行)。

下面是保存在iphone5上的空图片。长宽、大小都有,就是显示不出来。

以上。

4 回复

谢谢大佬们。我的问题已经解决了。

let unit = that.data.screenWidth / 375;

原因是这句代码,不兼容iphone5或者375 以下的屏幕宽度。加个条件判断,把unit在小于375的情况下的逻辑再实现一遍就好了。

但是更好的解决方式不是通过判断375来确定unit 而是__直接根据屏幕大小来画canvas__。

引以为戒!

另外,也__并不是官方给的这部分代码的错误__。

如果有同类问题,望规避。

你好,请提供一下出现问题的机型和微信版本,以及能复现问题的简单代码片段(https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html)。

绘制图片应该在wx.downloadFile成功的回调里进行,因为是异步下载的,所有要确保图片下载成功后才执行绘制

wx.downloadFile({

success: function(res) {

    this.drawImg()

}

})

回到顶部