在浏览器缩小时,地图拖动会有残影,看图:
原因是 在窗口缩小后,获取的 canvas宽高和实际的宽高不一致,导致clearRect清除不完全。
解决办法:
添加地图map dragging(或 dragend)事件,并获取页面的缩放比例。加大ctx.clearRect的大小。
看代码:
this.map = new window.BMap.Map('container-map')
this.setDepartMapCenter()
// 5. 开启鼠标滚轮缩放
this.map.enableScrollWheelZoom(true)
this.map.setMapStyleV2({ styleJson: styleJson3 })
this.map.addEventListener('zoomend', (e) => {
console.log('zoomend', this.map.getZoom())
})
//页面加载时就要记录缩放比例,
var zoomRatio = ChangeRatio();
//拖动地图时 也可以使用 dragend 事件。
this.map.addEventListener('dragging', (e) => {
//---注:获取浏览器缩放比例 不能放到事件里 因为这样原来缩小了,加载后又回到原来大小时,还是会清除不完整。----
//var zoomRatio = ChangeRatio();
console.log(zoomRatio,e.target.dT.width);
//只有页面缩小时才清除画布(移动时会闪)
if (zoomRatio < 1) {
//获取canvas context
var ctx = e.target.dT.getContext("2d");
//清除画布
ctx.clearRect(0, 0, e.target.dT.width/zoomRatio, e.target.dT.height/zoomRatio);
}
});
//------------------------------------------------------------
//获取浏览器缩放比例
function ChangeRatio() {
var ratio = 0;
var screen = window.screen;
var ua = navigator.userAgent.toLowerCase();
if (window.devicePixelRatio !== undefined) {
ratio = window.devicePixelRatio;
} else if (~ua.indexOf('msie')) {
if (screen.deviceXDPI && screen.logicalXDPI) {
ratio = screen.deviceXDPI / screen.logicalXDPI;
}
} else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
ratio = window.outerWidth / window.innerWidth;
}
// 注释
// if (ratio) {
// ratio = Math.round(ratio * 100);
// }
return ratio;
}