img.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. const config = require('../config');
  2. Component({
  3. options: {
  4. styleIsolation: 'shared'
  5. },
  6. properties: {
  7. data: {
  8. type: Object,
  9. value: {}
  10. }
  11. },
  12. data: {
  13. attr:{
  14. src:'',
  15. class:'',
  16. style:''
  17. },
  18. size:{
  19. w:0,
  20. h:0
  21. },
  22. styleObj:{}
  23. },
  24. lifetimes:{
  25. attached:function(){
  26. const _ts = this;
  27. let dataAttr = this.data.data.attrs;
  28. // 将图片大小处理到对象中
  29. if(dataAttr.width){
  30. _ts.data.size.w = +dataAttr.width / config.dpr;
  31. };
  32. if(dataAttr.height){
  33. _ts.data.size.h = +dataAttr.height / config.dpr;
  34. };
  35. // 将样式合并到样式对象中
  36. if(dataAttr.style){
  37. let re = /;\s{0,}/ig;
  38. dataAttr.style = dataAttr.style.replace(re,';');
  39. dataAttr.style.split(';').forEach(item => {
  40. let itemArr = item.split(':');
  41. if(/^(width|height)$/i.test(itemArr[0])){
  42. let num = parseInt(itemArr[1]) || 0,
  43. key = '';
  44. // itemArr[1] = num / config.dpr + itemArr[1].replace(num,'');
  45. switch (itemArr[0].toLocaleLowerCase()) {
  46. case 'width':
  47. key = 'w';
  48. break;
  49. case 'height':
  50. key = 'h';
  51. break;
  52. };
  53. _ts.data.size[key] = num / config.dpr;
  54. }else{
  55. _ts.data.styleObj[itemArr[0]] = itemArr[1];
  56. };
  57. });
  58. };
  59. // 设置公式图片
  60. _ts.setData({
  61. attrs:{
  62. src:dataAttr.src,
  63. class:dataAttr.class,
  64. style:_ts.setStyle(_ts.data.styleObj)
  65. },
  66. size:_ts.data.size
  67. });
  68. }
  69. },
  70. methods: {
  71. // 设置图片样式
  72. setStyle:function(o){
  73. let str = ``;
  74. for(let key in o){
  75. str += `${key}:${o[key]};`;
  76. };
  77. return str;
  78. },
  79. // 图片加载完成设置图片大小
  80. load:function(e){
  81. const _ts = this;
  82. if(!_ts.data.size.w || !_ts.data.size.h){
  83. _ts.setData({
  84. size:{
  85. w:e.detail.width / config.dpr,
  86. h:e.detail.height / config.dpr
  87. }
  88. });
  89. };
  90. }
  91. }
  92. })