仔细研究了下,发现实现起来并不难,核心代码只有下面10行。程序员
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: num,
height: num,
destWidth: num,
destHeight: num,
canvasId: 'shareImg',
success: function(res) {
that.setData({
prurl: res.tempFilePath
})
wx.hideLoading()
},
fail: function(res) {
wx.hideLoading()
}
})
复制代码
至于如何建立小程序,我这里就不在细讲了,我也有写过建立小程序的文章,也有路过相关的学习视频,去翻下我历史文章找找就行。canvas
布局很简单,只有下面几行代码。小程序
<!-- 画布大小按需定制 这里我按照背景图的尺寸定的 -->
<canvas canvas-id="shareImg"></canvas>
<!-- 预览区域 -->
<view class='preview'>
<image src='{{prurl}}' mode='aspectFit'></image>
<button size='mini' open-type="getUserInfo" bindgetuserinfo="shengcheng" data-k="1">生成头像1</button>
<button size='mini' open-type="getUserInfo" bindgetuserinfo="shengcheng" data-k="2">生成头像2</button>
<button size='mini' open-type="getUserInfo" bindgetuserinfo="shengcheng" data-k="3">生成头像3</button>
<button size='mini' open-type="getUserInfo" bindgetuserinfo="shengcheng" data-k="4">生成头像4</button>
<button type='primary' bindtap='save'>保存分享图</button>
</view>
复制代码
实现效果图以下 promise
其实咱们实现微信头像挂红旗,原理很简单,就是把头像放在下面,而后把有红旗的相框盖在头像上面 bash
let promise1 = new Promise(function(resolve, reject) {
wx.getImageInfo({
src: "../../images/xiaoshitou.jpg",
success: function(res) {
console.log("promise1", res)
resolve(res);
}
})
});
let promise2 = new Promise(function(resolve, reject) {
wx.getImageInfo({
src: `../../images/head${index}.png`,
success: function(res) {
console.log(res)
resolve(res);
}
})
});
Promise.all([
promise1, promise2
]).then(res => {
console.log("Promise.all", res)
//主要就是计算好各个图文的位置
let num = 1125;
ctx.drawImage('../../'+res[0].path, 0, 0, num, num)
ctx.drawImage('../../' + res[1].path, 0, 0, num, num)
ctx.stroke()
ctx.draw(false, () => {
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: num,
height: num,
destWidth: num,
destHeight: num,
canvasId: 'shareImg',
success: function(res) {
that.setData({
prurl: res.tempFilePath
})
wx.hideLoading()
},
fail: function(res) {
wx.hideLoading()
}
})
})
})
复制代码
来看下画出来的效果图 微信
save: function() {
var that = this
wx.saveImageToPhotosAlbum({
filePath: that.data.prurl,
success(res) {
wx.showModal({
content: '图片已保存到相册,赶忙晒一下吧~',
showCancel: false,
confirmText: '好哒',
confirmColor: '#72B9C3',
success: function(res) {
if (res.confirm) {
console.log('用户点击肯定');
}
}
})
}
})
}
复制代码
来看下保存后的效果图 ide