微信小程序 扩展组件绘制canvas


本文整理自网络,侵删。

wxml-to-canvas

小程序内通过静态模板和样式绘制 canvas ,导出图片,可用于生成分享图等场景。

使用方法

Step1. npm 安装

npm install --save wxml-to-canvas

Step2. JSON 组件声明

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

Step3. wxml 引入组件

<video class="video" src="{{src}}">
  <wxml-to-canvas class="widget"></wxml-to-canvas>
</video>
<image src="{{src}}" style="width: {{width}}px; height: {{height}}px"></image>

Step4. js 获取实例

const {wxml, style} = require('./demo.js')
Page({
  data: {
    src: ''
  },
  onLoad() {
    this.widget = this.selectComponent('.widget')
  },
  renderToCanvas() {
    const p1 = this.widget.renderToCanvas({ wxml, style })
    p1.then((res) => {
      this.container = res
      this.extraImage()
    })
  },
  extraImage() {
    const p2 = this.widget.canvasToTempFilePath()
    p2.then(res => {
      this.setData({
        src: res.tempFilePath,
        width: this.container.layoutBox.width,
        height: this.container.layoutBox.height
      })
    })
  }
})

wxml 模板

支持 view、text、image 三种标签,通过 class 匹配 style 对象中的样式。

<view class="container" >
  <view class="item-box red">
  </view>
  <view class="item-box green" >
    <text class="text">yeah!</text>
  </view>
  <view class="item-box blue">
      <image class="img" src="https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3582589792,4046843010&fm=26&gp=0.jpg" rel="external nofollow" ></image>
  </view>
</view>

样式

对象属性值为对应 wxml 标签的 cass 驼峰形式。需为每个元素指定 width 和 height 属性,否则会导致布局错误。

存在多个 className 时,位置靠后的优先级更高,子元素会继承父级元素的可继承属性。

元素均为 flex 布局。left/top 等 仅在 absolute 定位下生效。

const style = {
  container: {
    width: 300,
    height: 200,
    flexDirection: 'row',
    justifyContent: 'space-around',
    backgroundColor: '#ccc',
    alignItems: 'center',
  },
  itemBox: {
    width: 80,
    height: 60,
  },
  red: {
    backgroundColor: '#ff0000'
  },
  green: {
    backgroundColor: '#00ff00'
  },
  blue: {
    backgroundColor: '#0000ff'
  },
  text: {
    width: 80,
    height: 60,
    textAlign: 'center',
    verticalAlign: 'middle',
  }
}

接口

f1. renderToCanvas({wxml, style}): Promise

渲染到 canvas,传入 wxml 模板 和 style 对象,返回的容器对象包含布局和样式信息。

f2. canvasToTempFilePath({fileType, quality}): Promise

提取画布中容器所在区域内容生成相同大小的图片,返回临时文件地址。

阅读剩余部分

相关阅读 >>

微信小程序 运维中心getperformance

sdk数据库 command聚合操作符集合操作符

兼容

微信小程序 城市服务实名信息校验

微信小程序表单组件 picker-view(嵌入页面的滚动选择器)

微信小程序承载网页 web-view

微信小程序api 绘图对坐标轴进行顺时针旋转

微信小程序 setdevpluginapplystatus

微信小程序 插件调用api的限制

微信小程序 weui搜索组件

更多相关阅读请进入《微信小程序》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...