uniapp 代码工具
uniapp 代码工具
1.绘制canvas时文字换行,文字溢出两行显示…
function(ctx,t,x,y,w){
//参数说明
//ctx:canvas的 2d 对象,t:绘制的文字,x,y:文字坐标,w:文字最大宽度
let chr = t.split("")
let temp = ""
let row = []
for (let a = 0; a<chr.length;a++){
if( ctx.measureText(temp).width < w && ctx.measureText(temp+(chr[a])).width <= w){
temp += chr[a];
}else{
row.push(temp);
temp = chr[a];
}
}
row.push(temp)
for(let b=0;b<row.length;b++){
if(b==1&&row.length>=2){
//console.log('宽度',ctx.measureText(row[b]).width,w)
if(ctx.measureText(row[b]).width < w && row.length==2){
ctx.fillText(row[b],x,y+(b+1)*20)
}else{
ctx.fillText(row[b].slice(0,row[b].length-1)+'...',x,y+(b+1)*20)
}
}else if(b==0){
ctx.fillText(row[b],x,y+(b+1)*20);//每行字体y坐标间隔20
}
}
}
2.uniapp解码base64加密内容
function(base) {
var b = new Buffer(base, 'base64')
var s2 = b.toString(); // 转字符串
let data = decodeURIComponent(escape(s2))
return data
}
3.手机号码校验
function(phone) {
let regs = /^1[23456789]\d{9}$/;
return regs.test(phone)
}
4.上传图片 阿里oss方式 小程序
uploadImageApplet(event) {
return new Promise((resolve, reject) => {
const token = uni.getStorageSync('token')
var pathList = [];
uni.chooseImage({
count: event.count || 9,
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths;
uni.showLoading({
title: '上传中'
})
let obj = new Date()
let day = obj.getDate()
let month = obj.getMonth() + 1
let year = obj.getFullYear()
for (let i = 0; i < tempFilePaths.length; i++) {
let index = tempFilePaths[i].lastIndexOf(".")
let suffix = tempFilePaths[i].substr(index + 1)
let fileList = uni.getStorageSync('user').id + '/' + Math.random().toString(36).substr(2) +
'.' + suffix
//获取oss签名
uni.request({
url: api + 'oss_getSign',
data: {
token: token
},
method: 'POST',
header: {
"Content-Type": store.state.requestHeader,
authentication : token
},
})
.then((res) => {
uni.uploadFile({
url: store.state.globalupApi,
filePath: tempFilePaths[i],
name: event.name ? event.name : 'file',
formData: {
'key': fileList,
'policy': res[1].data.data.policy, // 输入你获取的的policy
'OSSAccessKeyId': res[1].data.data.accessid, // 输入你的AccessKeyId
'success_action_status': 200, // 让服务端返回200,不然,默认会返回204
'signature': res[1].data.data.signature // 输入你获取的的signature
},
header: {
"Content-Type": "multipart/form-data",
authentication : token
},
success: (uploadFileRes) => {
let key = store.state.globalupApi + fileList
let breviary = store.state.globalupApi + fileList +
'?x-oss-process=image/resize,s_600,m_fill,limit_0'
let square = store.state.globalupApi + fileList +
'?x-oss-process=image/resize,s_600,m_fill,limit_0'
pathList.splice(i, 0, {
type: 0,
key: key,
breviary: breviary,
square: square
})
if (pathList.length == tempFilePaths.length) {
resolve(pathList)
uni.hideLoading();
}
}
})
})
}
}
});
})
}
5.上传图片 阿里oss方式 h5
uploadImageH5(event) {
return new Promise((resolve, reject) => {
const token = uni.getStorageSync('token')
var pathList = [];
uni.chooseImage({
count: event.count || 9,
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths;
const tempFiles = chooseImageRes.tempFiles;
uni.showLoading({
title: '上传中'
})
let obj = new Date()
let day = obj.getDate()
let month = obj.getMonth() + 1
let year = obj.getFullYear()
for (let i = 0; i < tempFilePaths.length; i++) {
let index = tempFiles[i].name.lastIndexOf(".")
let suffix = tempFiles[i].name.substr(index + 1)
let fileList = uni.getStorageSync('userId') + '/' + Math.random().toString(36).substr(2) +
'.' + suffix
console.log('tempFilePaths[i]',tempFilePaths[i])
//获取oss签名
uni.request({
url: api + `/restful/common/oss/aliyun/sign/${uni.getStorageSync('userId')}`,
data: {
token: token
},
method: 'GET',
header: {
"Content-Type": store.state.requestHeader,
Authentication : token
},
})
.then((res) => {
// console.log('res',res)
uni.uploadFile({
url: updateApi,
filePath: tempFilePaths[i],
name: event.name ? event.name : 'file',
formData: {
'key': fileList,
'policy': res[1].data.data.policy, // 输入你获取的的policy
'OSSAccessKeyId': res[1].data.data.accessId, // 输入你的AccessKeyId
'success_action_status': 200, // 让服务端返回200,不然,默认会返回204
'signature': res[1].data.data.signature // 输入你获取的的signature
},
header: {
Authentication : token
},
success: (uploadFileRes) => {
// console.log('uploadFileRes',uploadFileRes)
let key = uni.getStorageSync('oss_url') + fileList
let breviary = uni.getStorageSync('oss_url') + fileList +
'?x-oss-process=image/resize,s_600,m_fill,limit_0'
let square = uni.getStorageSync('oss_url') + fileList +
'?x-oss-process=image/resize,s_600,m_fill,limit_0'
pathList.splice(i, 0, {
type: 0,
key: key,
breviary: breviary,
square: square
})
// console.log('上传成功',pathList)
if (pathList.length == tempFilePaths.length) {
resolve(pathList)
uni.hideLoading();
}
},
fail:(err)=>{
console.log('上传失败',err)
}
})
})
}
}
});
})
}
6.接口获取二进制流数据转图片
function(res) { //res是二进制流数据
// 1,得到文件管理
const fileSystemManager = uni.getFileSystemManager();
// 2,拼接路径
const codeFilePath = `${wx.env.USER_DATA_PATH}/adv.png`
// 3,写入临时文件
fileSystemManager.writeFileSync(codeFilePath, res, "binary")
return codeFilePath
}
7.微信小程序订阅通知
function(ids) {
// 获取用户当前设置
wx.getSetting({
withSubscriptions:true,
success: (res) => {
if(res.subscriptionsSetting.mainSwitch){
wx.requestSubscribeMessage({
tmplIds:ids,
success:(res)=>{
console.log('通知消息订阅成功',res)
},
fail:(error)=>{
console.log('通知消息订阅失败',error)
}
})
}else{
uni.showModal({
title:'提示',
content:'是否允许小程序向您发送通知消息?',
success(modal_res) {
if(modal_res.confirm){
wx.openSetting({
withSubscriptions:true,
success(res) {
console.log('打开消息通知')
}
})
// 授权系统通知消息订阅
wx.requestSubscribeMessage({
tmplIds:ids,
success:(res)=>{
console.log('通知消息订阅成功',res)
}
})
}
}
})
}
}
})
}
8.小程序端文档预览下载
关于下载文档:打开文档后,文档右上角会有一个按钮,点击按钮后,安卓手机里面有保存文件的选项;iOS手机会有发送给朋友的选项,可以在聊天记录里面拿到这个文件
function(url) { //url是文档链接
uni.showLoading({
title:'正在下载中,请稍候...',
mask:true
})
wx.downloadFile({
url,//下载地址接口返回
success: (data) => {
console.log('downloadFile success',data)
if (data.statusCode === 200) {
wx.openDocument({
filePath: data.tempFilePath,
showMenu:true, //关键点
success: function(res) {
console.log('打开文档成功');
uni.hideLoading()
}
});
}
},
fail: (err) => {
console.log(err);
uni.hideLoading()
uni.showToast({
icon: 'none',
mask: true,
title: '失败请重新下载',
});
},
});
}