wxml:
事件触发:
<button class="saoBtn" bindtap='savePhoto'>保存图片</button>
画布显示:
<view class="placeHoder"></view>
<canvas hidden='{{isShow}}' style="width:{{canvasWidth}}px; height:{{canvasHeight}}px;" canvas-id="myCanvas"/>
js:
savePhoto:function () {
wx.showLoading({
title: '绘制中',
})
console.log('点击保存图片')
let that = this
wx.downloadFile({
url: 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3220589324,939421850&fm=26&gp=0.jpg', // 绘制的第一张图片的下载路径
success(res) {
wx.hideLoading();
// 创建画布对象
const ctx = wx.createCanvasContext("myCanvas", that)
// 获取图片信息,要按照原图来绘制,否则图片会变形
wx.getImageInfo({
src: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201607%2F24%2F20160724175133_XEUNM.thumb.700_0.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1612429377&t=56c95e35415945dd8566ae93d4033f6d',
success:function(res){
// 根据 图片的大小 绘制底图 的大小
console.log(" 绘制底图 ", res)
let imgW = res.width
let imgH = res.height
let imgPath = res.path
that.setData({
canvasHeight: imgH,
canvasWidth:imgW
})
ctx.drawImage(imgPath, 33, 38, imgW, imgH)
// 合成人像
wx.getImageInfo({
src: 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=255676174,1347478056&fm=26&gp=0.jpg', // 第二张图片路径
success:function(res){
console.log(" 绘制第二张图", res)
// 绘制二维码,图片固定为300px,留白50px,固定在图片右下角,具体放置位置 你可以进行计算,因为画布的大小你是知道的,所以确定位置也很简单
ctx.drawImage(res.path, imgW - 500,
imgH - 500,
300, 300)
ctx.draw()
// 这里用了延时截屏,防止图片没加载完成,截图出现白屏的现象
setTimeout(() => {
wx.canvasToTempFilePath({
canvasId: 'myCanvas',
success: function (res) {
var tempFilePath = res.tempFilePath
// 保存到相册
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(res) {
// 修改下载状态
let imgs = that.data.imgs
that.setData({
imgs: imgs,
})
wx.hideLoading()
wx.showModal({
title: '温馨提示',
content: '图片保存成功,可在相册中查看',
showCancel: false
})
},
fail(res) {
wx.hideLoading()
wx.showModal({
title: '温馨提示',
content: '图片保存失败,请重试',
showCancel: false
})
}
})
// that.setData({
// isShow: true
// })
console.log("生成的图片", tempFilePath)
},
fail: function (res) {
console.log("生成的图片 失败 fail fail fail ",res)
}
}, this)
}, 1500) },
})
}
})
}
})
}