js
<h3>扁平化数组</h3>
<pre><code>//利用 Array.float(depth) //infinity表示可展开任意深度
funciton flatten (params){
return params.float(infinity)
}
// toString
function flatten(params){
return params.toString().split(',').map(item=>parseFloat(item))
}
//递归
function flatten(params){
let result=[]
params.forEach(item=>{
if(Array.isArray(item)){
result =result.concat(flatten(item))
}else{
result.push(item)
}
})
return result
}
</code></pre>
<h3>uni 图片上传</h3>
<pre><code>// 摄像头授权
getCameraSetting () {
uni.authorize({
scope:'scope.camera',
success: (res) => {
console.log(res, '已打开摄像头权限')
},
fail: () => {
uni.showModal({
title:'友情提示',
content:'检测到您没打开摄像头权限,是否去设置打开?',
confirmText: '去设置',
success: (res) => {
if(res.confirm) uni.openSetting()
}
})
}
})
},
// 上传图片前
async beforeUpload(index){
let file = await that.chooseImage(index)
let base64 = ''
if((file.size / 1024 / 1024) > that.maxSize){
// 大于2M,先进行压缩
base64 = await that.compressImage(file)
// 压缩完重新判断图片大小
if((that.getImgByteSize(base64) / 1024 / 1024) > that.maxSize){
that.$u.toast('图片不可超上限2MB!')
return false
}
}else{
// 小于2M,直接上传
base64 = 'data:image/jpeg;base64,' + uni.getFileSystemManager().readFileSync(file.path, 'base64')
}
// 上传图片
that.uploadImg(base64, index)
},
// 选择图片
chooseImage(index){
return new Promise((resolve, reject)=>{
uni.chooseImage({
count: 1,
sourceType: ['album', 'camera'],
sizeType: ['original', 'compressed'],
success: async function(res){
let file = res.tempFiles[0]
that.imgs[index].preview = file.path //图片预览
resolve(file) // 返回选定照片的本地文件路径列表
},
fail: function(err) {
reject()
}
})
})
},
// 压缩图片
compressImage(file){
return new Promise((resolve, reject) => {
uni.getImageInfo({
src: file.path,
success: function (image) {
const imgWidth = image.width;
const imgHeight = image.height;
// 图片尺寸压缩比例处理 ==> 计算出画布宽高
let dp = 1;
if (that.compressWidth > 0 && that.compressHeight == 0) {
const wdp = imgWidth / that.compressWidth;
dp = wdp > 1 ? wdp : 1;
} else if (that.compressWidth == 0 && that.compressHeight > 0) {
const hdp = imgHeight / that.compressHeight;
dp = hdp > 1 ? hdp : 1;
} else if (that.compressWidth > 0 && that.compressHeight > 0) {
const wdp = imgWidth / that.compressWidth;
const hdp = imgHeight / that.compressHeight;
dp = wdp > hdp ? wdp : hdp;
dp = dp > 1 ? dp : 1;
}
that.ctxWidth = parseInt(imgWidth/dp)
that.ctxHeight = parseInt(imgHeight/dp)
//canvas宽高重新设置后会有一段渲染的间隔,这个间隔可能导致画到画布的图片出现大小不一致的bug,这里做下300ms延迟处理兼容
setTimeout(()=>{
const ctx = uni.createCanvasContext("myCanvas")
ctx.clearRect(0, 0, that.ctxWidth, that.ctxHeight)
ctx.drawImage(file.path, 0, 0, that.ctxWidth, that.ctxHeight)
ctx.draw(false, ()=>{
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
x: 0,
y: 0,
width: that.ctxWidth,
height: that.ctxHeight,
destWidth: that.ctxWidth,
destHeight: that.ctxHeight,
quality: that.quality,
fileType: 'jpg',
success: function(res) {
const result = 'data:image/jpeg;base64,' + uni.getFileSystemManager().readFileSync(res.tempFilePath, 'base64')
resolve(result)
}
})
})
}, 300)
}
});
})
},
// 计算base64图片大小(不太准确)
getImgByteSize(base64Str) {
const equalIndex = base64Str.indexOf('='); // 获取=号下标
if (equalIndex > 0) {
const str = base64Str.substring(0, equalIndex); // 去除=号
const strLength = str.length;
const fileLength = strLength - (strLength / 8) * 2; // 真实的图片byte大小
return Math.floor(fileLength); // 向下取整
} else {
const strLength = base64Str.length;
const fileLength = strLength - (strLength / 8) * 2;
return Math.floor(fileLength); // 向下取整
}
},
// 单独上传图片接口
uploadImg(file, index){
that.$u.post(Api.stock_imgs, {
img: file,
loading: 1
}).then(res=>{
if(res.code == 200){
that.imgs[index].previewImg = res.data
}else{
that.$u.toast(res.msg)
}
})
},
// 删除图片
delImg(index){
that.imgs.splice(index, 1)
},</code></pre>
<h3>判断配置文件是否开启日志调试 是否输出日志 true 输出 | false 不输出</h3>
<pre><code>let logDebug = false;
console.log = (function(oriLogFunc) {
return function() {
if (logDebug) {
oriLogFunc.apply(this, arguments);
}
}
})(console.log)</code></pre>
<h4>easycom组件模式</h4>
<pre><code>//pages.json
// HBuilderX 2.5.5起支持easycom组件模式
"easycom": {
"autoscan": true,
"custom": {
"^u-(.*)": "@/uview-ui/components/u-$1/u-$1.vue", //匹配uView组件
"^h-(.*)": "@/components/h-$1/h-$1.vue" //匹配hana自定义组件
}
},</code></pre>
<h4>页面添加水印</h4>
<pre><code>/**
* waterWrapper 批量加水印 2022-10-31
* @param {*} waterWidth 水印宽
* @param {*} waterHeight 水印高
* @param {*} innerText 水印内容
*/
function waterWrapper(waterWidth = 180, waterHeight = 100, innerText = '花苗业务管理系统'){
$('.water-wrapper').remove(); // resize时,清除之前的水印元素
// 创建水印最外层div
const waterWrapper = document.createElement('div')
waterWrapper.className = 'water-wrapper'
cssHelper(waterWrapper, {
position: 'fixed',
top: '0',
right: '0',
bottom: '0',
left: '0',
overflow: 'hidden',
display: 'flex',
'flex-wrap': 'wrap',
'pointer-events': 'none',
'z-index': '100000'
})
// 计算文档能放得下多少个水印
const { clientWidth, clientHeight } = document.documentElement || document.body
const column = Math.ceil(clientWidth / waterWidth)
const rows = Math.ceil(clientHeight / waterHeight)
for (let i = 0; i < column * rows; i++) {
const wrap = document.createElement('div')
cssHelper(wrap, Object.create({
position: 'relative',
width: `${waterWidth}px`,
height: `${waterHeight}px`,
flex: `0 0 ${waterWidth}px`,
overflow: 'hidden',
}))
wrap.appendChild(createItem(innerText))
waterWrapper.appendChild(wrap)
}
$('body').append(waterWrapper)
}
// 创建具体水印
function createItem(innerText) {
const item = document.createElement('div')
item.innerHTML = innerText
cssHelper(item, {
position: 'absolute',
top: `50px`,
left: `50px`,
fontSize: `16px`,
color: '#000',
lineHeight: 1.5,
opacity: 0.05,
transform: `rotate(-15deg)`,
transformOrigin: '0 0',
userSelect: 'none',
whiteSpace: 'nowrap',
overflow: 'hidden',
})
return item
}
// 遍历添加样式
function cssHelper(el, prototype) {
for (let i in prototype) {
el.style[i] = prototype[i]
}
}</code></pre>