Newer
Older
KaiFengPC / public / static / libs / mapbox / extend / CanvasLayer.js
@zhangdeliang zhangdeliang on 23 May 5 KB 初始化项目
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ?
  3. module.exports = factory() :
  4. typeof define === 'function' && define.amd ? define(factory) :
  5. (global = typeof globalThis !== 'undefined' ? globalThis :
  6. global || self, global.mapboxgl1.CanvasLayer = factory());
  7. }(window,(function(){
  8.  
  9. function loadAllImages(imgUrls) {
  10. var _load = function (imgUrl) {
  11. //创建img标签
  12. var img = new Image();
  13. img.src = imgUrl;
  14. //跨域选项
  15. img.setAttribute('crossOrigin', 'Anonymous');
  16. return new Promise((resolve, reject) => {
  17. //文件加载完毕
  18. img.onload = function () {
  19. resolve(img);
  20. };
  21. //文件加载失败处理
  22. img.onerror = function () {
  23. console.log(imgUrl);
  24. reject();
  25. };
  26. });
  27. };
  28. var _loadAll = function (imgUrls) {
  29. var loadedImageUrls = [];
  30. for (var i = 0, len = imgUrls.length; i < len; i++) {
  31. loadedImageUrls.push(_load(imgUrls[i]));
  32. }
  33. return loadedImageUrls;
  34. };
  35. return Promise.all(_loadAll(imgUrls));
  36. }
  37.  
  38. function generateUUID() {
  39. let d = new Date().getTime();
  40. let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
  41. let r = (d + Math.random()*16)%16 | 0;
  42. d = Math.floor(d/16);
  43. return (c=='x' ? r : (r&0x3|0x8)).toString(16);
  44. });
  45. return uuid;
  46. }
  47.  
  48. return class CanvasLayer {
  49. id=null;
  50. map=null;
  51. images=[];
  52. type="raster";
  53. canvas=null;
  54. params=null;
  55. index=0;
  56. loaded=false;
  57. constructor(options={id:'',canvasId:'',bbox:undefined,images:undefined,width:undefined,height:undefined,callback:()=>{}}) {
  58. this.canvas = document.getElementById(options.canvasId);
  59. if(!(this.canvas)) {
  60. this.canvas = document.createElement('canvas');
  61. this.canvas.setAttribute("id", options.canvasId || generateUUID());
  62. }
  63. if(!(options.images.length)) console.warn(`Please set the photo set! → images:${options.images}`);
  64. if(!(options.bbox)) console.warn(`Please set the bbox! → images:${options.bbox}`);
  65. if(!options.width || !options.height) console.warn(`Please set the canvas width and height! → width:${options.width};height:${options.height}`);
  66. this.params = options;
  67. this.id = options.id || generateUUID();
  68. loadAllImages(options.images).then(res => this.images = res, this.loaded = true,options.callback && options.callback());
  69. }
  70.  
  71. remove(){
  72. if(!this.map) return console.warn(`Please trigger "addTo" This method is called after the "map" instance is passed in;`);
  73. let layer = this.map.getLayer(this.id);
  74. if(!layer) return console.warn(`The current layer has not been added to the map;`);
  75. this.map.removeLayer(this.id);
  76. this.map.removeSource(this.id);
  77. }
  78.  
  79. addTo(map){
  80. if(!map) return console.warn(`Configure the map instance;`);
  81. this.map = map;
  82. if(!this.params.bbox || !this.params.bbox.length) return console.error(`The current object is missing important parameters. Please add them and trigger the method again; url:${this.params.url};url:${this.params.layers}`);
  83. let coordinates = [
  84. [this.params.bbox[0],this.params.bbox[3]],
  85. [this.params.bbox[2],this.params.bbox[3]],
  86. [this.params.bbox[2],this.params.bbox[1]],
  87. [this.params.bbox[0],this.params.bbox[1]],
  88. ];
  89. this.map.addSource(this.id, {'type':'canvas',coordinates,canvas:this.canvas,animate:true});
  90. this.map.addLayer({'id':this.id, 'type':this.type, 'source': this.id});
  91. }
  92.  
  93. show(){
  94. this.setLayerParams({visibility:'visible'});
  95. }
  96.  
  97. hide(){
  98. this.setLayerParams({visibility:'none'});
  99. }
  100.  
  101. setOpacity(opacity){
  102. this.setLayerParams({},{'raster-opacity':opacity});
  103. }
  104.  
  105. async setInitializeParams(params={}){
  106. this.loaded = false;
  107. this.params = Object.assign(this.params,params);
  108. let res = await loadAllImages(this.params.images);
  109. if(this.params.bbox) this.map.getSource(this.id).setCoordinates([[this.params.bbox[0],this.params.bbox[3]], [this.params.bbox[2],this.params.bbox[3]], [this.params.bbox[2],this.params.bbox[1]], [this.params.bbox[0],this.params.bbox[1]]]);
  110. this.images = res;
  111. this.loaded = true;
  112. this.index= 0;
  113. params.callback && params.callback();
  114. }
  115.  
  116. setLayerParams(layout={},paint={}){
  117. let layoutKeys = Object.keys(layout);
  118. let paintKeys = Object.keys(paint);
  119. layoutKeys.forEach(key => this.map.setLayoutProperty(this.id,key,layout[key]));
  120. paintKeys.forEach(key => this.map.setPaintProperty(this.id,key,paint[key]));
  121. }
  122.  
  123. prev(time=1000){
  124. let flag =false;
  125. let opacity = 1;
  126. let step = 1;
  127. let stepNum = opacity / step;
  128. let interval = setInterval(()=> {
  129. if(!flag) opacity = Number((opacity - stepNum).toFixed(2));
  130. if(opacity == 0) flag = true,this.setIndex(this.index - 1);
  131. // console.log(opacity,this.index);
  132. if(flag) opacity = Number((opacity + stepNum).toFixed(2));
  133. this.refresh(opacity);
  134. if(opacity == 1) clearInterval(interval);
  135. },time / step);
  136. }
  137.  
  138. next(time=1000){
  139. let flag =false;
  140. let opacity = 1;
  141. let step = 1;
  142. let stepNum = opacity / step;
  143. let interval = setInterval(()=> {
  144. if(!flag) opacity = Number((opacity - stepNum).toFixed(2));
  145. if(opacity == 0) flag = true,this.setIndex(this.index + 1);
  146. // console.log(opacity,this.index);
  147. if(flag) opacity = Number((opacity + stepNum).toFixed(2));
  148. this.refresh(opacity);
  149. if(opacity == 1) clearInterval(interval);
  150. },time / step);
  151. }
  152.  
  153. setIndex(index){
  154. index = index<0?this.params.images.length-1:index;
  155. index = this.params.images.length<=index?0:index;
  156. this.index = index;
  157. }
  158.  
  159. refresh(alpha=1){
  160. if(!this.loaded) return;
  161. this.canvas.width = this.params.width;
  162. this.canvas.height = this.params.height;
  163. let context = this.canvas.getContext('2d');
  164. context.globalAlpha = alpha;
  165. context.drawImage(this.images[this.index], 0, 0, this.params.width, this.params.height);
  166. }
  167. }
  168. })));