目標(biāo)
- 應(yīng)用uni-app框架(或者原生微信小程序同理)
- 使用
Canvas
繪制自定義的二維碼、文字畫布
- 將畫布轉(zhuǎn)化成可供
分享保存
的圖片
解決方案
方案1
- 定義一個二維碼臨時canvas,如
canvas-id="myCanvas"
; 以及 繪制完整海報canvas,如canvas-id="myQrcode"
<!-- 先繪制二維碼 -->
<canvas :style="{ width: qrcode_w + 'px', height: qrcode_h + 'px', position: 'absolute', left: 0, bottom: '-' + qrcode_h + 'px' }"
canvas-id="myCanvas" class="my-canvas"></canvas>
<!-- 繪制所有內(nèi)容 -->
<canvas :style="{ width: qrcode_w2 + 'px', height: qrcode_h2 + 'px', position: 'absolute', left: 0, bottom: '-' + qrcode_h2 + 'px' }"
canvas-id="myQrcode"></canvas>
- 使用封裝過的
weapp.qrcode.min.js
進行生成動態(tài)二維碼叨襟,并在回調(diào)函數(shù) callback 獲取圖片資源的網(wǎng)絡(luò)路徑
import QRCode from '@/utils/weapp.qrcode.min.js';
// 繪制二維碼
drawQrCode() {
new QRCode('myCanvas', {
// colorLight: '#ffcc66',
// colorDark: "#ffcc66",
width: this.qrcode_w,
height: this.qrcode_h,
text: `https://canteen.xiangdaoyun.com/upload/qrcode/promoter/?key=f7cf8ab98e9f41be81a60c76073aca46`,
padding: this.getPxToRpx(100), // 生成二維碼四周自動留邊寬度,不傳入默認為0
correctLevel: QRCode.CorrectLevel.L, // 二維碼可辨識度
callback: (res) => {
// 接下來就可以直接調(diào)用微信小程序的api保存到本地或者將這張二維碼直接畫在海報上面去,看各自需求
console.log('二維碼: -> ' + res.path)
this.drawAll(res.path)
}
})
}
- 運用微信小程序api
CanvasContext.drawImage
咒吐,將上述2中的網(wǎng)絡(luò)路徑的圖片資源,繪制圖像到畫布2中:myQrcode
// 繪制完整海報
drawAll(qrcodePath) {
// canvas創(chuàng)建畫圖
const ctx = wx.createCanvasContext('myQrcode');
// 繪制背景圖
ctx.setFillStyle('#fff')
ctx.fillRect(0, 0, this.qrcode_w2, this.qrcode_h2)
// 繪制二維碼
ctx.drawImage(qrcodePath, 0, 0, this.qrcode_w, this.qrcode_h);
// 繪制字體属划,顏色恬叹,與位置
ctx.setFontSize(14)
ctx.setFillStyle('#474747')
ctx.setTextAlign('center')
ctx.fillText('測試文字', this.getPxToRpx(300), this.getPxToRpx(620))
ctx.fillText(uni.$dateUtil.format(new Date(), 'yyyy-MM-dd HH:mm:ss'), this.getPxToRpx(300), this.getPxToRpx(680))
// canvasToTempFilePath必須要在draw的回調(diào)中執(zhí)行,否則會生成失敗同眯,官方文檔有說明
ctx.draw(false, setTimeout(() => {
uni.canvasToTempFilePath({
x: 0,
y: 0,
width: this.qrcode_w2,
height: this.qrcode_h2,
destWidth: this.qrcode_w2 * 2,
destHeight: this.qrcode_h2 * 2,
canvasId: 'myQrcode',
success: (res) => {
// 繪制成功后绽昼,使用預(yù)覽圖片api,展示二維碼海報
console.log('生成最終海報: -> ' + res.tempFilePath);
uni.hideLoading();
uni.previewImage({
current: res.tempFilePath, // 當(dāng)前顯示圖片的http鏈接
urls: [res.tempFilePath]
})
},
fail: (err) => {
console.log(err);
uni.hideLoading();
uni.showToast({
title: '生成失敗',
icon: "none"
})
}
})
}, 200));
}
方案2(只演示方案1须蜗,可做訓(xùn)練)
- 定義一個二維碼臨時canvas硅确,如
canvas-id="myCanvas"
; 以及 繪制完整海報canvas明肮,如canvas-id="myQrcode"
- 使用
weapp.qrcode.min.js
進行在 畫布1 myCanvas
生成動態(tài)二維碼
- 使用
wx.canvasToTempFilePath
菱农,將畫布1 myCanvas
中的二維碼導(dǎo)出來,生成 res.tempFilePath 網(wǎng)絡(luò)路徑的圖片資源
- 運用微信小程序api
CanvasContext.drawImage
柿估,將上述2中的網(wǎng)絡(luò)路徑的圖片資源循未,繪制圖像到畫布2中:myQrcode
提示
- canvas可以使用
絕對定位
設(shè)置到界面之外,控制隱藏顯示(根據(jù)自身需要)
- canvas在繪制draw的時候官份,不可以設(shè)置
display: none
的隱藏效果只厘,否則繪制不出(和Echarts圖表類庫同理)