微信小程序wxml-to-canvas 的使用以及遇到的坑

1.首先根据官网提示安装即可

npm install --save wxml-to-canvas

2.构建NPM

这一步很关键,在微信开发者工具左上角-》工具-》npm构建。
PS:我第一次用的时候就忘了我构建了

3.引入组件

  
  // class="widget"  这里不能删。

4.获取实例

  ready(){    //组件中使用这个周期   页面中使用 onLoad(){}
    this.widget = this.selectComponent('.widget')
    setTimeout(() => {
      const p1 = this.widget.renderToCanvas({
        wxml,
        style
      })
      p1.then((res) => {
        console.log('container', res.layoutBox)
        this.container = res
      })
    }, 500)
  }
//刚进入页面 的时候renderToCanvas()并没有被创建。所以我使用了一个定时器

5.wxml 模板

支持 view、text、image 三种标签,通过 class 匹配 style 对象中的样式。
注意:需为每个元素指定 width 和 height 属性,否则会导致布局错误。
元素均为 flex 布局。left/top 等 仅在 absolute 定位下生效。

坑1:宽高被限制,里面的内容无法显示完全。

组件默认是由固定的宽高的

需要在组件中给定宽高,比如我项目中就给定了高

坑2:背景图引入无效

1.首先下载引入官方demo,然后在node_modules/wxml-to-canvas/miniprogram_dist/index.js 里边,找到并复制如下代码:

async drawImage(img, box, style) {
    await new Promise((resolve, reject) => {
      const ctx = this.ctx
      const canvas = this.canvas
      const {
        borderRadius = 0
      } = style
      const {
        left: x, top: y, width: w, height: h
      } = box
      ctx.save()
      this.roundRect(x, y, w, h, borderRadius, false, false)
      ctx.clip()
      const Image = canvas.createImage()
      Image.onload = () => {
        ctx.drawImage(Image, x, y, w, h)
        ctx.restore()
        resolve()
      }
      Image.onerror = () => { reject() }
      Image.src = img
    })
  }

复制后找到 自己项目所对应的node_modules/wxml-to-canvas/miniprogram_dist/index.js中,粘贴(覆盖)原来所对应的代码即可。
微信小程序wxml-to-canvas 的使用以及遇到的坑_第1张图片
微信小程序wxml-to-canvas 的使用以及遇到的坑_第2张图片

你可能感兴趣的:(微信小程序,小程序)