先是在uni-app的插件庫找了N個插件,都會報錯??
canvasToTempFilePath: fail canvas is empty
搜了各種解決方案,都不行,只能棄用uni-app的插件,可能是因為版本的原因,小程序的canvas已經改成了原生的canvas
可以在uni-app項目中引用原生的wxml-to-canvas
1.官網鏈接:https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/extended/component-plus/wxml-to-canvas.html
2.打開代碼片段代碼片段
3.在程序中新建wxcomponents文件夾,將代碼片段中的miniprogram_npm下的widget-ui和wxml-to-canvas兩個文件夾復制進去
4.將/wxcomponents/wxml-to-canvas/index.js中的module.exports = require("widget-ui");引用路徑改成module.exports = require("../widget-ui/index.js");
5.配置pages.json(這樣uni-app才會打包wxcomponents)
"pages": [
{
"path": "components/articleShare",
"style": {
"usingComponents": {
"wxml-to-canvas": "/wxcomponents/wxml-to-canvas/index"
}
}
}
wxml-to-canvas的使用問題
1. 要在彈出框unipopup中展示canvas有問題
由于需求是要在彈出框中展示canvas,但是wxml-to-canvas是在生命周期attached中就初始化了canvas信息,但此時canvas元素是彈出框被隱藏(可見源碼/wxcomponents/wxml-to-canvas/index.js第160行,或搜索attached)
解決辦法:
思路:等對話框彈出后,再初始化canvas
- 在
methods中添加initCanvas方法,將上述attatched中的代碼剪切進去 - 在彈出對話框的方法中調用如下
open() {
uni.showLoading();
//先彈出對話框
this.$refs.popup.open("center");
this.$nextTick(() => {
//等對話框展示后,調用剛剛添加的方法
this.$refs.widget.initCanvas();
// 延時,等canvas初始化
setTimeout(() => {
this.renderToCanvas();
}, 500); attached
});
},
2. wxml-to-canvas要注意的一些問題
- 只能畫view,text,img
- 每個元素必須要設置寬高
- 默認是flex布局,可以通過
flexDirection: "column"來改變排列方式
3. 如何畫出自適應的canvas(由于默認是px單位,所以要改源代碼來實現自適應)
思路:用屏幕的寬度/設計圖的寬度
第一步,修改/wxcomponents/wxml-to-canvas/index.js
- 在
attached生命周期中,獲取設備的寬度,拿到屏幕寬度比率
lifetimes: {
attached() {
const sys = wx.getSystemInfoSync();
//拿到設備的寬度,跟設計圖寬度的比例
const screenRatio = sys.screenWidth / 375;
this.setData({
screenRatio,
width: this.data.width * screenRatio,
height: this.data.height * screenRatio,
});
},
},
- 修改
initCanvas方法中的代碼
// canvas.width = res[0].width * dpr;
// canvas.height = res[0].height * dpr;
//以上代碼改為如下代碼
canvas.width = this.data.width * dpr;
canvas.height = this.data.height * dpr;
- 修改
renderToCanvas方法
//const { wxml, style } = args;
//改為
const { wxml, fnGetStyle } = args;
const style = fnGetStyle(this.data.screenRatio)
第二步,修改傳入renderToCanvas的sytle對象改為函數fnGetStyle(屏幕的寬度比率)
const fnGetStyle = (screenRatio) => {
return {
share: {
backgroundColor: "#fff",
//所有數值都要拿設計圖上的數值再乘以屏幕寬度比率
width: 320 * screenRatio,
height: 395 * screenRatio,
padding: 24 * screenRatio,
},
...
}
The EndshareImage