本文整理自网络,侵删。
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
提取画布中容器所在区域内容生成相同大小的图片,返回临时文件地址。
相关阅读 >>
微信小程序apisettextbaseline(设置文字水平对齐)
微信小程序组件 contact-button(客服会话按钮)
更多相关阅读请进入《微信小程序》频道 >>

Vue.js 设计与实现 基于Vue.js 3 深入解析Vue.js 设计细节
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者