1、考慮到組件復(fù)用,所以我把它做成一個(gè)自定義的組件
<my-poster
id="getPoster"
avater="{{imageUrl}}"
knowledges="{{klPoster}}"
scene="{{topicId}}">
</my-poster>
可以傳圖片avater、文字內(nèi)容knowledges、頁面參數(shù)scene
2、組件里面首先是得需要一個(gè)畫布。
畫布外可以正常寫元素標(biāo)簽,定義樣式
<view class="mask_screen" wx:if="{{showpost}}">
<view class='poster_box'>
<view class='poster_content' id='canvas-container'>
<canvas canvas-id="myCanvas" style="width:100%;height:{{canvasHeight}}px;" />
</view>
<view class='tips'>保存圖片,分享給小伙伴吧</view>
<view class='save' bindtap='saveShareImg'>
<image class='down' mode='widthFix' src='../../assets/dbs/down.png'></image>
<text>保存</text>
</view>
<image class='close' bindtap='closePoste' mode='widthFix' src='../../assets/dbs/close.png'></image>
</view>
</view>
3、畫布準(zhǔn)備好之后,就是需要準(zhǔn)備畫圖的一些資源,比如圖片之類的
網(wǎng)絡(luò)圖片需利用微信接口 wx.downloadFile 下載下來之后,獲取圖片的臨時(shí)地址,根據(jù)該臨時(shí)地址才可以畫圖;
如果是工程類圖片,只需要寫好路徑,即可以畫圖。比如:
// 網(wǎng)絡(luò)圖片
if (topicImage) {
wx.downloadFile({
url: topicImage,
success: function(res) {
wx.hideLoading();
if (res.statusCode === 200) {
var productSrc = res.tempFilePath;
that.calculateImg(productSrc, function(data) {
that.getCode(productSrc, data)
})
}
}
})
}
// 工程內(nèi)圖片
let dbicon = '../../assets/dbs/' + item.type + '.png';
ctx.drawImage(dbicon, 15, offsetHeight + 10, 10, 10)
4、有些圖片可能要計(jì)算寬高的,需要利用微信接口 wx.getImageInfo 獲取圖片寬高等信息,wx.getSystemInfo 獲取手機(jī)屏幕寬高等信息,根據(jù)比例去計(jì)算繪制
//計(jì)算圖片尺寸
calculateImg: function(src, cb) {
var that = this;
wx.getImageInfo({
src: src,
success(res) {
wx.getSystemInfo({
success(res2) {
var ratio = res.width / res.height;
var imgHeight = res2.windowWidth * 0.6 / ratio;
// var screeRratio = res2.screenWidth / res2.screenHeight
that.setData({
canvasHeight: imgHeight + 280
// canvasHeight: res2.windowWidth * 0.5 / screeRratio
})
cb(imgHeight);
}
})
}
})
}
5、再就是獲取頁面的小程序碼,微信文檔有介紹:三種接口獲取方式
獲取小程序碼:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html
6、繪制文字換行問題,上一篇有介紹
7、圖片生成之后,保存圖片。主要利用微信接口 wx.canvasToTempFilePath 和 wx.saveImageToPhotosAlbum
//點(diǎn)擊保存到相冊(cè)
saveShareImg: function() {
var that = this;
wx.showLoading({
title: '正在保存',
mask: true,
})
setTimeout(function() {
wx.canvasToTempFilePath({
canvasId: 'myCanvas',
success: function(res) {
wx.hideLoading();
var tempFilePath = res.tempFilePath;
wx.saveImageToPhotosAlbum({
filePath: tempFilePath,
success(res) {
wx.showModal({
content: '圖片已保存到相冊(cè),趕緊曬一下吧~',
showCancel: false,
confirmText: '好的',
confirmColor: '#333',
success: function(res) {
that.closePoste();
if (res.confirm) {}
},
fail: function(res) {
console.log(res)
}
})
},
fail: function(res) {
wx.showToast({
title: res.errMsg,
icon: 'none',
duration: 2000
})
}
})
},
fail: function(err) {
console.log(err)
}
}, that);
}, 1000);
},
8、注意事項(xiàng):
(1)圖片要提前下載:這里面有一個(gè)問題就是,圖片要提前下載完之后再繪圖,不然圖片顯示不出來,可以把下載圖片的方法單獨(dú)拎出來,然后下載圖片后回調(diào)繪圖方法。
(2)ctx.draw(),這個(gè)方法是在繪制完成之后在調(diào)用,不然容易其它被覆蓋。
大致思路就是如此。