小程序绘制
1.wxml结构
<view id='canvas_box' class='canvas_box'>
<canvas canvas-id="canvas_cover" class="canvas_cover" ></canvas>
</view>
2. //引入base64.js
const base64 = require('../../utils/base64.js')
//创建base64.js文件,复制下面代码,保存
const fsm = wx.getFileSystemManager();
function base64src(base64data, cb) {
const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
if (!format) {
return (new Error('ERROR_BASE64SRC_PARSE'));
}
const filePath = `${
wx.env.USER_DATA_PATH}/${
new Date().getTime()}.${
format}`;
const buffer = wx.base64ToArrayBuffer(bodyData);
fsm.writeFile({
filePath,
data: buffer,
encoding: 'binary',
success() {
setTimeout(() => {
fsm.removeSavedFile({
filePath
})
},100);
cb(filePath);
},
fail() {
return (new Error('ERROR_BASE64SRC_WRITE'));
},
});
};
export {
base64src };
3.//封装方法
buildBossImg: function (download) {
let self = this;
new Promise((resolve,reject)=>{
// 排行数据
let self = this;
let value = wx.getStorageSync('userType'); // !!value?1:2 3-18都展示所有
statisticsService.getStatisticalRank({
businessId: self.data.businessId,
taskId: self.data.taskId,
sort: 1,
type: 0,
pageIndex: 1,
pageSize: 3
}, (err, res) => {
res.data.employeeList.forEach((item) => {
//字数长度处理
if (item.name){
item.name = item.name.length > 4 ? item.name.substring(0, 4) : item.name;
}
if (item.nickname){
item.nickname = item.nickname.length > 4 ? item.nickname.substring(0, 4) : item.nickname;
}
})
res.data.customerList.forEach((item) => {
if (item.nickname){
item.nickname = item.nickname.length > 4 ? item.nickname.substring(0, 4) : item.nickname
}
})
self.setData({
rankList: res.data
})
resolve(self.data.rankList)
})
}).then((result)=>{
wx.createSelectorQuery().in(this).select('.canvas_box').fields({
size: true
}, (box) => {
console.log('开始绘图',box);
let rate = box.width / 580,
employeeList = result.employeeList,
customerList = result.customerList,
paintData = self.data.paintData;
let
qrcodeInfo = {
source: null,
size: {
width: 75,
height: 75
}
};
const ctx = wx.createCanvasContext('canvas_cover', this);
//绘制文字超出打点
function fillText(ctx, str, fontSize, color, x, y) {
ctx.setTextBaseline('top');
ctx.setFontSize(fontSize);
ctx.setFillStyle(color);
// ctx.fillText(str, x, y);
let maxWidth = box.width - x,
maxLength = Math.floor(maxWidth / fontSize);
if (str.length <= maxLength) {
ctx.fillText(str, x, y, maxWidth);
} else {
ctx.fillText(str.substring(0, maxLength - 3) + '...', x, y, maxWidth);
}
}
Promise.