仔細研究了下,發現實現起來並不難,核心代碼只有下面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
到這裏,個人微信頭像就成功的加上了小紅旗了。 源碼我也已經給你們準備好了,有須要的同窗在文末留言便可。 後面我準備錄製一門課程出來,來詳細教你們實現這個功能,敬請關注。