当前位置:网站首页>Wechat applet plug-in -- wxml to canvas (generate pictures)
Wechat applet plug-in -- wxml to canvas (generate pictures)
2022-07-26 19:25:00 【Eat fish and spit bubbles】
One 、 demand
In the project, we need to realize a function of sharing pictures to the circle of friends , Turn the generated poster into a picture and save it to your mobile phone . Yes wxml-to-canvas plug-in unit .
Two 、 Official example usage
1. install wxml-to-canvas
npm install --save wxml-to-canvas
2.JSON Component declaration
{
"usingComponents": {
"wxml-to-canvas": "wxml-to-canvas",
}
}
3.wxml Import components
<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>
4. js Get instance
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
})
})
}
})
3、 ... and 、 Actual project
install 、json To configure 、wxml The introduction is the same .
1.wxml
<wxml-to-canvas class="widget" width="325" height="550"></wxml-to-canvas>
<view class='save flex-center-center' bindtap='preservation'>
Save the poster
</view>2.js file
const net = require('../../../common/network.js');
//️ Poster content and style
const { wxml, style } = require('./canvas.js');
// Self encapsulated wechat api
import wxApi from '../../../common/wxApi';
const app = getApp();
Page({
/**
* Initial data of the page
*/
data: {
},
/**
* Life cycle function -- Monitor page loading
*/
onLoad(options) {
wx.showLoading({
title: ' Poster generation in progress ...',
});
// Get the initial data of the page
this.getServerData();
},
getServerData() {
net.posterInfo().then((response) => {
const { name, title, teacher, qr_code, task_id } = response.data;
const { real_name, avatarurl, nickname } = app.globalData.userInfo;
// Data used to draw posters
this.setData({
info: response.data,
avatarurl,
name,
title,
teacher,
qr_code,
});
// Be careful ️: Here is the initial rendering of the page
this.widget = this.selectComponent('.widget');
const _wxml = wxml(name, avatarurl, title, teacher, qr_code);
//onload The node in the method is not loaded , Set the timer
setTimeout(() => {
// Render to canvas, Pass in wxml Templates and style object , The returned container object contains layout and style
// Information .
const p1 = this.widget.renderToCanvas({
wxml: _wxml,
style,
});
p1.then((res) => {
this.container = res;
wx.hideLoading();
});
}, 500);
});
},
preservation() {
// this.widget = this.selectComponent('.widget')
const { task_id } = this.data;
const p2 = this.widget.canvasToTempFilePath();
p2.then((res) => {
// Save to local album
wxApi.apiScopeOauth('scope.writePhotosAlbum').then(() => {
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(res) {
util.showToast(
' Poster saved , Go to the circle of friends to share !',
'none',
3000
);
},
fail(res) {
wx.showToast({
icon: 'error',
title: ' Failed to save picture !',
});
},
});
});
}).catch((fail) => {
wx.showToast({
icon: 'error',
title: ' Please try again later ',
});
});
},
});
3.canvas.js
Show only the general framework , The specific content related to privacy is removed .
wxml The returned string is the page content .
const wxml = ( name, avatarurl,title,teacher,qr_code ) => {
return `
<view class="poster-wapper">
<image class="poster-img" src="https://1.png"/>
<view class="author">
<text class="author-text"> author :${name}</text>
</view>
<view class="head">
<view class="head-border">
<image class="head-img" src="${avatarurl}"></image>
</view>
</view>
<view class="poster-info">
<view class="info">
<text class="title"> Challenge content :《${title}》</text>
`+ (teacher?`<text class="teacher"> teacher :${teacher}</text>`:'')
+` <view class="line"></view>
<text class="tip"> This reading is almost perfect ! Come and listen !</text>
</view>
<image class="qrcode-img" src="${qr_code}" />
</view>
</view>
`
}
const style = {
posterWapper:{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
position: 'relative',
},
posterImg: {
width: 325,
height: 550
},
author: {
width: 119,
height: 32,
borderRadius: 12,
backgroundColor: 'rgba(255,255,255,0.8)',
position: 'absolute',
paddingLeft: 18,
top: 353,
left: 45,
},
authorText: {
width: 98,
height: 32,
paddingLeft: 13.5,
fontSize: 11,
fontWeight: 600,
color: '#333333',
verticalAlign: 'middle',
},
head: {
width: 51,
height: 51,
borderRadius: 25.5,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
position: 'absolute',
top: 343,
left: 12,
backgroundColor: 'rgba(255,255,255,0.8)',
},
headBorder: {
width: 46,
height: 46,
backgroundColor: 'rgba(255,255,255)',
borderRadius: 23,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
headImg: {
width: 43,
height: 43,
borderRadius: 20,
},
posterInfo:{
position: 'absolute',
bottom: -6,
width: 325,
height: 143,
backgroundColor: '#FFFFFF',
borderRadius: 10,
display: 'flex',
flexDirection: 'row'
},
info: {
width: 210,
height: 140,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
paddingTop: 6,
paddingLeft: 15
},
title: {
width: 210,
height: 24,
fontSize: 13,
fontWeight: 600,
color: '#333333',
lineHeight: 24
},
teacher:{
width: 210,
height: 24,
fontSize: 13,
fontWeight: 400,
color: '#666666',
lineHeight: 24,
},
line:{
width: 190,
height: 1,
backgroundColor: 'rgba(3,0,0,0.16)'
},
tip: {
height: 24,
width: 210,
fontSize: 13,
fontFamily: 'PingFang SC',
fontWeight: 600,
color: '#333333',
lineHeight: 24,
},
btn:{
width: 140,
height: 33,
backgroundColor: '#FF6000',
borderRadius: 19,
lineHeight: 33,
textAlign: 'center',
marginTop: 7.5,
position: 'relative'
},
btnText:{
width: 140,
height: 33,
fontSize: 18,
fontFamily: 'PingFang SC',
fontWeight: 600,
color: '#FFFFFF',
},
btnImg:{
width:37,
height:18,
position: 'absolute',
left: 150,
top: 9
},
qrcodeImg:{
width: 92,
height: 92,
marginLeft: 5,
position: 'absolute',
bottom: 33,
right: 12
}
}
module.exports = {
wxml,
style
}
Be careful ️:
1.wxml Support view、text、image Three kinds of labels , adopt class matching style Styles in objects .
2.css Object property value is corresponding to wxml Labeled class Hump form . You need to specify... For each element width and height attribute , Otherwise, it will lead to wrong layout .
3. There are multiple className when , The lower priority is higher , The child element inherits the inheritable properties of the parent element .
The elements are flex Layout .left/top etc. Only in absolute Take effect under positioning .
4.css Background pictures are not supported , stay wxml of use img Instead of .
5. Writing text The label must be covered with a layer of view label , Otherwise it doesn't show .( This is the problem I encountered , I don't know if it's stipulated like this )
边栏推荐
- 销量下滑,品牌边缘化,失去“安全牌”的沃尔沃,还能走多远?
- .net CLR GC dynamic loading transient heap threshold calculation and threshold excess calculation
- 香港高防IP优势及哪些行业适合使用
- [swoole series 3.1] have you been asked about processes, threads, and collaborations during the interview?
- Advanced template (runner's notes)
- ReentrantLock学习之公平锁过程
- Data Lake -- concept, characteristics, architecture and case overview
- 时空预测5-GAT
- 2022g1 industrial boiler stoker certificate question bank and simulation examination
- MySQL主从复制配置详解
猜你喜欢

PMP practice once a day | don't get lost in the exam -7.26 (including agility + multiple choices)

MySQL learning notes -2. how to improve the query performance of SQL statements

2022g1 industrial boiler stoker certificate question bank and simulation examination

2022 mobile crane driver test questions simulation test platform operation

彻底关闭win10自动更新

The difference between advanced anti DDoS server and advanced anti DDoS IP

Customer cases | focus on process experience to help bank enterprise app iteration

Mathematical basis of deep learning

Advantages of advanced anti DDoS IP in Hong Kong and which industries are suitable for use
![[postgraduate entrance examination vocabulary training camp] day 13 - reliance, expert, subject, unconscious, photograph, exaggeration, counter act](/img/9c/0e6e8abebfd3afdeef2913281a6ada.png)
[postgraduate entrance examination vocabulary training camp] day 13 - reliance, expert, subject, unconscious, photograph, exaggeration, counter act
随机推荐
MySQL日志介绍
2022g1 industrial boiler stoker certificate question bank and simulation examination
什么是服务器集群?海外服务器集群的优势?
ReentrantLock学习之---基本属性
JS uses readLine to realize terminal input data
从6月25日考试之后,看新考纲如何复习PMP
2022t elevator repair examination questions and online simulation examination
[AUTOSAR RTE] - 1-talk about RTE (run time environment)
JVM内存模型之Volatile关键字
指标和标签是做什么的
手写一个Starter
Racher deploys kubernetes cluster
How far can Volvo, which has lost its "safety brand" due to declining sales and marginalization of its brand?
Onion group joined hands with oceanbase to realize distributed upgrading, and global data has achieved cross cloud integration for the first time
Typescript stage learning
Write a starter
基础模块及算例#pytorch学习
Distributed transaction Seata
手机申请公募reits账户安全吗?
MapReduce(二)