utils.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. let utils = {
  2. guid:function() {
  3. function S4() {
  4. return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
  5. }
  6. return S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4()
  7. },
  8. getStorage:function(name) {
  9. let value = window.localStorage.getItem(name);
  10. try {
  11. const temp = JSON.parse(value);
  12. let nowDate = new Date();
  13. let expireDate = new Date(temp.expire);
  14. if (temp) {
  15. if (temp.expire) {
  16. if (nowDate < expireDate) {
  17. return temp.token
  18. } else {
  19. return null;
  20. }
  21. } else {
  22. return temp
  23. }
  24. } else {
  25. return null;
  26. }
  27. } catch (e) {
  28. return value;
  29. }
  30. },
  31. setStorage:function(name, value) {
  32. if (value.expire) {
  33. value.expire = new Date().getTime() + value.expire * 1000;
  34. }
  35. window.localStorage.setItem(name, JSON.stringify(value));
  36. },
  37. //格式化日期
  38. formatDate:function(str) {
  39. let date = new Date(str * 1000);
  40. const year = date.getFullYear();
  41. const month = date.getMonth() + 1;
  42. const day = date.getDate();
  43. return [year, month, day].map(formatNumber).join('-');
  44. },
  45. //格式化时间
  46. formatTime:function(str) {
  47. let date = new Date(str * 1000);
  48. const year = date.getFullYear();
  49. const month = date.getMonth() + 1;
  50. const day = date.getDate();
  51. const hour = date.getHours();
  52. const minute = date.getMinutes();
  53. const second = date.getSeconds();
  54. return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':');
  55. },
  56. //加0
  57. formatNumber:function(n) {
  58. n = n.toString();
  59. return n[1] ? n : '0' + n;
  60. },
  61. getBase64Image:function(img) {
  62. var canvas = document.createElement("canvas");
  63. canvas.width = img.width;
  64. canvas.height = img.height;
  65. var ctx = canvas.getContext("2d");
  66. ctx.drawImage(img, 0, 0, img.width, img.height);
  67. var dataURL = canvas.toDataURL("image/png"); // 可选其他值 image/jpeg
  68. return dataURL;
  69. },
  70. main:function(src, cb) {
  71. var image = new Image();
  72. image.src = src + '?v=' + Math.random(); // 处理缓存
  73. image.crossOrigin = "*"; // 支持跨域图片
  74. image.onload = function () {
  75. var base64 = getBase64Image(image);
  76. cb && cb(base64);
  77. }
  78. },
  79. // 处理文件大小
  80. handleSize:function(size) {
  81. if ((size / 1024 / 1024) < 1) {
  82. return (size / 1024).toFixed(2) + 'KB';
  83. } else {
  84. return (size / 1024 / 1024).toFixed(2) + 'MB';
  85. }
  86. }
  87. }