百度地图 map api 解决“当浏览器缩小时,拖动地图时,画布不能全部清除”的问题。

在浏览器缩小时,地图拖动会有残影,看图:

 

 原因是 在窗口缩小后,获取的 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;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值