etms_wechat_mini_oem/yunbainian/etms_wechat_mini/utils/util.js

122 lines
3.2 KiB
JavaScript
Raw Normal View History

2024-12-06 16:18:22 +08:00
const formatTime = (date) => {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
return `${[year, month, day].map(formatNumber).join("/")} ${[
hour,
minute,
second,
]
.map(formatNumber)
.join(":")}`;
};
const formatNumber = (n) => {
n = n.toString()
return n[1] ? n : `0${n}`
};
const isDownloadFileSuccess = async (filePath) => {
return new Promise((resolve, reject) => {
wx.downloadFile({
url: filePath,
success(res) {
if (res.statusCode === 200) {
resolve(true);
} else {
resolve(false);
}
},
fail() {
resolve(false);
},
});
});
};
const compareVersion = (v1, v2) => {
v1 = v1.split(".");
v2 = v2.split(".");
const len = Math.max(v1.length, v2.length);
while (v1.length < len) {
v1.push("0");
}
while (v2.length < len) {
v2.push("0");
}
for (let i = 0; i < len; i++) {
const num1 = parseInt(v1[i], 10);
const num2 = parseInt(v2[i], 10);
if (num1 > num2) {
return 1;
} else if (num1 < num2) {
return -1;
}
}
return 0;
};
/**
* canvas能否正常渲染图片
* @param {string} url 图片URL
* @param {string} canvasId
* @param {*} thisArg 页面实例
* @returns
*/
const isCreateImageSuccess = (url, canvasId, thisArg) => {
return new Promise((resolve, reject) => {
const {
SDKVersion
} = wx.getSystemInfoSync();
const use2dCanvas = compareVersion(SDKVersion, "2.9.2") >= 0;
if (use2dCanvas) {
const query = thisArg.createSelectorQuery();
query
.select(`#${canvasId}`)
.fields({
node: true,
size: true
})
.exec((res) => {
console.log({
res
});
const canvas = res[0].node;
const ctx = canvas.getContext("2d");
canvas.width = res[0].width;
canvas.height = res[0].height;
const Image = canvas.createImage();
Image.onload = () => {
ctx.drawImage(Image, 0, 0, res[0].width, res[0].height);
ctx.restore();
resolve(true);
};
Image.onerror = (e) => {
console.log(e);
resolve(false);
};
Image.src = url;
});
} else {
wx.showToast({
title: '您的微信SDK版本低不支持该功能',
icon: 'none', //icon
duration: 1500 //停留时间
})
}
});
};
module.exports = {
isDownloadFileSuccess,
compareVersion,
isCreateImageSuccess,
formatTime,
};