微信小程序中使用wxml-to-canvas

  • Post author:
  • Post category:小程序

1. 下载:

npm install wxml-to-canvas –save

2. json文件导入

"usingComponents": {
    "wxml-to-canvas": "wxml-to-canvas/index"
},

3、使用组件

 index.wxml

<wxml-to-canvas width="350" height="550" class="widget"></wxml-to-canvas>
<button bindtap="extraImage">保存图片</button>

index.js

const { wxmls, style } = require('./demo.js')
let widget = null
Page({
 data: {
    
  },
 onLoad(options) {
    wx.showLoading({
      title: '图片生成中。。',
    })
     this.widget = this.selectComponent('.widget')
    // 必须要用定时器延迟,不然会报错
    setTimeout(()=>{
      this.renderToCanvas()
    },150)   
 },
  //生成海报
  renderToCanvas() {
    let obj = {
        avatar: '头像.png',
        topImg: '头部.png',
        contentBg: '内容背景.png'
    }
    // 传入要填入的动态数据
    let wxml = wxmls(obj)
    const p1 = this.widget.renderToCanvas({ wxml, style })
    p1.then((res) => {
       wx.hideLoading()
    })
  },
//保存海报
  extraImage() {
    const p2 = this.widget.canvasToTempFilePath()
    p2.then(res => {
      console.log(res)
      wx.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success(res) {
          console.log(res)
        }
      })
    }).catch(err=>{
      console.log(err)
    })
  }
})

demo.js中的配置

const wxmls = (info) => {
  return `
  <view class="container">
      <image class="bg" src="BG.jpg">                            
      </image>
      <image class="topImg" src="${info.topImg}"></image>
      <view class="content">
        <image class="contentBg" src="${info.contentBg}"></image>
        <view class="portrait">
          <image class="avatar" src="${info.avatar}"></image>
          <image class="frame" src="frame.png"></image>
        </view>
      </view>
    </view>
  `
}

const style = {
  container: {
    position: 'relative',
    width: 350,
    height: 550,
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  },
  bg: {
    position: 'absolute',
    left: 0,
    top: 0,
    width: 350,
    height: 550,
  },
  topImg: {
    position: 'relative',
    width: 270,
    height: 120,
    marginTop: 40
  },

  content: {
    position: 'relative',
    width: 270,
    height: 270,
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  },
  contentBg: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: 270,
    height: 270
  },
  portrait: {
    position: 'relative',
    width: 100,
    height: 100,
    marginTop: -50,
    borderRadius: '50',
    overflow: 'hidden',
  },

  frame: {
    width: 100,
    height: 100,
    position: 'absolute',
    left: 0,
    top: 0,
  },

  avatar: {
    width: 100,
    height: 100,
    borderRadius: 50,
  }
}

module.exports = {
  wxmls,
  style
}


版权声明:本文为m0_49440146原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。