uni-app小程序使用wxml-to-canvas实现海报分享

先是在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)
第二步,修改传入renderToCanvassytle对象改为函数fnGetStyle(屏幕的宽度比率)
const fnGetStyle = (screenRatio) => {
  return {
    share: {
      backgroundColor: "#fff",
      //所有数值都要拿设计图上的数值再乘以屏幕宽度比率
      width: 320 * screenRatio,
      height: 395 * screenRatio,
      padding: 24 * screenRatio,
    },
    ...
}

The EndshareImage

你可能感兴趣的:(uni-app小程序使用wxml-to-canvas实现海报分享)