前端時間公司的業務里,需要自動將背景圖和用戶輸入的標題生成封面并上傳至OSS的需求,感覺以后會用到,因此記錄一下。
一.將頁面生成圖片
使用了 2.0庫插件()。
step-01:下載demo,將組件放入自己的小程序下。step-02:在需要生成圖片的頁面文件夾下增加.js文件
// canvas.js
module.exports = data => {
return (
{
"width": "620px",
"height": "980px",
"background": "#ffffff",
"views": [
{
"type": "text",
"text": data.name,
"css": {
"color": "#191846",
"background": "rgba(0,0,0,0)",
"width": "536px",
"top": "486px",
"left": "41px",
"rotate": "0",
"borderRadius": "",
"borderWidth": "",
"borderColor": "#000000",
"shadow": "",
"fontSize": "30px",
"lineHeight": "43px",
"fontWeight": "normal",
"textStyle": "fill",
"textDecoration": "none",
"fontFamily": "",
"textAlign": "left"
}
},
]
}
);
}
step-03:在需要生成圖片的頁面js中引入。
import canvas from './canvas.js';
painterBtn() {
let name="我是傳遞的參數";
this.setData({
// wxml: canvas(name) // 在此傳遞參數
wxml:{
width: "654rpx",
height: "1000rpx",
//背景圖片資源
background: "/assets/2.jpg",
//根據自己所需的樣式在view中配置。
views: [
{
type: "text",
text: "標題標題標題",
css: {
fontFamily: "Bitstream Vera Serif Bold",
width:"300rpx",
textAlign:"center",
fontWeight:800,
top: "400rpx",
fontSize: "56rpx",
},
}]
}
})
wx.showLoading({
title: '正在生成中...',
})
},
onImgOK(e) {
console.log(e);
//e.detail.path為圖片路徑
this.setData({
src: e.detail.path
})
wx.hideLoading()
wx.getFileSystemManager().readFile({
filePath: e.detail.path, //選擇圖片返回的相對路徑
encoding: 'base64', //編碼格式
success: result => { //成功的回調
let file = 'data:image/png;base64,' + result.data;
//業務代碼
}
})
}
頁面wxml代碼
<!-- 這個是生成的海報圖片預覽 -->
<image src="{{src}}" style="height:980rpx" mode="aspectFit" class="canvas-img"></image>
<!-- 這個是painter組件使用 -->
<painter palette="{{wxml}}" style="position: absolute; top: -9999rpx;" bind:imgOK="onImgOK" />
<!-- 生成海報按鈕 -->
<button bindtap="painterBtn">生成海報</button>
至此圖片就生成啦。可以拿到圖片的路徑和。 二.上傳到OSS服務器
由于我們公司的OSS后端有接口可以獲取到上傳至OSS所需的參數。我就只貼出調用微信上傳文件至OSS的代碼
wx.uploadFile({
url: “你的OSS服務地址”,
filePath: e.detail.path,
name: 'file',
header: {
"Content-Type": "multipart/form-data"
},
formData: {
name:e.detail.path,
key: key,
policy: policyy,
OSSAccessKeyId: accessid,
signature: signature
},
//調用成功的回調
success(r) {
}
})
ok!