我想制作一个简单的 Canvas 层(不是平铺 Canvas ,而是一个大 Canvas ),但我找不到如何将图层放在 mapPane
之外以使其不可拖动有记录的方式。
我应该使用“未记录”的方法还是应该使用“反向转换”黑客?
最佳答案
如果我理解正确的话,您希望将自己的 Canvas 覆盖到 Leaflet map 上,但这样它就不会与 map 的其余部分(如平铺图层或标记)一起平移(被拖动)。
因此,它就像一个控件(如缩放、图层切换和属性控件),相对于 map 容器保持在相同位置,只不过它会覆盖整个 map View 端口。
正如您似乎已经想到的那样,一旦您将元素插入 map pane ,当用户拖动/平移时,它将与其余 map 元素一起移动。
因此,您可以简单地将其附加到 map 容器中,作为 map Pane 的同级:
// http://leafletjs.com/reference-1.3.0.html#map-getcontainer
map.getContainer().appendChild(myCanvasElement);
然后您需要调整 Canvas 元素的 CSS:
- 绝对定位
- 位于其他同级控件上方( map Pane 具有
z-index
of 400 ,但您可能希望保持在其他控件下方,这些控件具有z-index
of 1000 ) - 让鼠标事件通过(以便用户仍然可以使用 map 对象,例如单击标记等)
#myCanvasElement {
position: absolute;
/* Let mouse events go through to reach the map underneath */
pointer-events: none;
/* Make sure to be above the map pane (.leaflet-pane) */
z-index: 450;
}
工作代码片段示例:
var map = L.map('map').setView([48.86, 2.35], 11);
var myCanvasElement = document.getElementById('myCanvasElement');
// Adjust the canvas size, assuming we want to cover the entire map.
var mapSize = map.getSize(); // http://leafletjs.com/reference-1.3.0.html#map-getsize
myCanvasElement.width = mapSize.x;
myCanvasElement.height = mapSize.y;
// Move the canvas inside the map container.
var mapContainer = map.getContainer(); // http://leafletjs.com/reference-1.3.0.html#map-getcontainer
mapContainer.appendChild(myCanvasElement);
// Draw on the canvas...
var context = myCanvasElement.getContext('2d');
context.strokeStyle = 'rgb(0, 0, 200)';
var w = 200;
var h = 100;
var x = (mapSize.x - w) / 2;
var y = (mapSize.y - h) / 2;
context.strokeRect(x, y, w, h);
L.marker([48.86, 2.35]).bindPopup('Paris').addTo(map);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
#myCanvasElement {
position: absolute;
/* Let mouse events go through to reach the map underneath */
pointer-events: none;
/* Make sure to be above the map pane (.leaflet-pane) */
z-index: 450;
}
<link rel="stylesheet" href="https://unpkg.com/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c1ada4a0a7ada4b581f0eff2eff0" rel="noreferrer noopener nofollow">[email protected]</a>/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<script src="https://unpkg.com/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="244841454248415064150a170a15" rel="noreferrer noopener nofollow">[email protected]</a>/dist/leaflet-src.js" integrity="sha512-IkGU/uDhB9u9F8k+2OsA6XXoowIhOuQL1NTgNZHY1nkURnqEGlDZq3GsfmdJdKFe1k1zOc6YU2K7qY+hF9AodA==" crossorigin=""></script>
<div id="map" style="height: 180px"></div>
<canvas id="myCanvasElement"></canvas>
关于LeafletJS : How to make layer not movable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49184531/