utils.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. let windowWidth = uni.getSystemInfoSync().windowWidth
  2. // uni-app@2.9起, 屏幕最多适配到960, 超出则按375计算
  3. if (windowWidth > 960) windowWidth = 375
  4. export const rpx2px = (value) => {
  5. if (typeof value === 'string') value = Number(value.replace(/[a-z]*/g, ''))
  6. return windowWidth / 750 * value
  7. }
  8. export const changeUnits = (value) => {
  9. return Number(value.replace(/^(\-*[0-9.]*)([a-z%]*)$/, (value, num, unit) => {
  10. switch (unit) {
  11. case 'px':
  12. num *= 1
  13. break
  14. case 'rpx':
  15. num = rpx2px(num)
  16. break
  17. default:
  18. num *= 1
  19. break
  20. }
  21. return num
  22. }))
  23. }
  24. export const resolveImage = async (img, canvas, srcName = 'src', resolveName = '$resolve') => {
  25. let imgObj
  26. // 区分 H5 和小程序
  27. if (window) {
  28. imgObj = new Image()
  29. } else {
  30. imgObj = canvas.createImage()
  31. }
  32. // 成功回调
  33. imgObj.onload = () => {
  34. img[resolveName](imgObj)
  35. }
  36. // 失败回调
  37. imgObj.onerror = (err) => {
  38. console.error(err)
  39. // img['$reject']()
  40. }
  41. // 设置src
  42. imgObj.src = img[srcName]
  43. }
  44. // 旧版canvas引入图片的方法
  45. // export const resolveImage = async (res, img, imgName = 'src', resolveName = '$resolve') => {
  46. // const src = img[imgName]
  47. // const $resolve = img[resolveName]
  48. // // #ifdef MP
  49. // // 如果是base64就调用base64src()方法把图片写入本地, 然后渲染临时路径
  50. // if (/^data:image\/([a-z]+);base64,/.test(src)) {
  51. // const path = await base64src(src)
  52. // $resolve({ ...res.detail, path })
  53. // return
  54. // }
  55. // // #endif
  56. // // 如果是本地图片, 直接返回
  57. // if (src.indexOf('http') !== 0) {
  58. // $resolve({ ...res.detail, path:src })
  59. // return
  60. // }
  61. // // 如果是网络图片, 则通过getImageInfo()方法获取图片宽高
  62. // uni.getImageInfo({
  63. // src: src,
  64. // success: (imgObj) => $resolve(imgObj),
  65. // fail: () => console.error('API `uni.getImageInfo` 加载图片失败', src)
  66. // })
  67. // }
  68. export function getImage(canvasId, canvas) {
  69. return new Promise((resolve, reject) => {
  70. uni.canvasToTempFilePath({
  71. canvas,
  72. canvasId,
  73. success: res => resolve(res),
  74. fail: err => reject(err)
  75. }, this)
  76. })
  77. }