44<转载>arcgis api for js 4.x 叠加自定义图片
原文地址:https://xiaozhuanlan.com/topic/6591843207 版权归原作者所有
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" /> <title>Custom DynamicLayer - 4.12</title> <link rel="stylesheet" href="https://js.arcgis.com/4.12/esri/themes/light/main.css" /> <style> html, body, #viewDiv { padding: 0; margin: 0; height: 100%; width: 100%; } </style> <script src="https://js.arcgis.com/4.12/"></script> </head> <body> <div id="viewDiv"></div> <script> require([ "esri/Map", "esri/Basemap", "esri/views/MapView", "esri/layers/BaseDynamicLayer", "esri/layers/TileLayer", "esri/core/urlUtils" ], function (Map, Basemap, MapView, BaseDynamicLayer, TileLayer) { //自定义叠加图片图层 var CustomImageOverlayLayer = BaseDynamicLayer.createSubclass({ properties: { picUrl: null, extent: null, image: null, canvas: null, }, // Override the getImageUrl() method to generate URL // to an image for a given extent, width, and height. getImageUrl: function (extent, width, height) { //新Image对象,可以理解为DOM if (!this.image) { this.image = new Image(); } this.image.src = this.picUrl; // 创建canvas DOM元素,并设置其宽高和图片一样 if (!this.canvas) { this.canvas = canvas = document.createElement("canvas"); } this.canvas.width = 2000; this.canvas.height = 2000; //左上角坐标转换屏幕坐标,为了获取canvas绘制图片的起点 var mapPoint = { x: this.extent.xmin, y: this.extent.ymax, spatialReference: { wkid: 4326 } }; var screenPoint = view.toScreen(mapPoint); //根据extent范围计算canvas绘制图片的宽度以及高度 //左下角 var leftbottom = { x: this.extent.xmin, y: this.extent.ymin, spatialReference: { wkid: 4326 } }; var screen_leftbottom = view.toScreen(leftbottom); //右上角 var righttop = { x: this.extent.xmax, y: this.extent.ymax, spatialReference: { wkid: 4326 } }; var screen_righttop = view.toScreen(righttop); this.canvas.getContext("2d").drawImage(this.image, screenPoint.x, screenPoint.y, Math.abs(screen_righttop.x - screen_leftbottom.x), Math.abs(screen_righttop.y - screen_leftbottom.y)); return this.canvas.toDataURL("image/png"); } }); var layer = new TileLayer({ url: "http://server.arcgisonline.com/arcgis/rest/services/ESRI_Imagery_World_2D/MapServer" }); var imgBasemap = new Basemap({ baseLayers: [layer] }); map = new Map({ basemap: imgBasemap, }); view = new MapView({ container: "viewDiv", map: map, center: [113.36795152905626, 23.1278045049863], zoom: 12 }); view.when(function () { var ImageOverlayLayer = new CustomImageOverlayLayer({ picUrl: "0.png", extent: { xmin: 113.3596, ymin: 23.1239, xmax: 113.3748, ymax: 23.1354 } }); map.add(ImageOverlayLayer); //地图移动刷新,防止地图初始化时候,图片叠加图层加载刷新不过来 setTimeout(function () { var center = view.center.clone(); center.x -= 0.001;//底图是经纬度 view.center = center; view.goTo(view.center, { speedFactor: 0.1, easing: "linear" //linear, in-cubic, out-cubic, in-out-cubic, in-expo, out-expo, in-out-expo }); }, 500); }, function (error) { console.log("The view's resources failed to load: ", error); }); }); </script> </body> </html>