ArcGIS API for Javascript解决html2canvas、domtoimage截图地图出现空白问题

原因

使用html2canvas、domtoimage进行截图时,会出现地图面板是空白的情况,报错如下:

#1 133ms Unable to clone WebGL context as it has preserveDrawingBuffer=false <canvas style=​"width:​ 100%;​ height:​100%;​ >

在通过ArcGIS API for JavaScript 4.X版本实例化地图的时候,我们的底图是通过canvas元素绘制出来的,canvas无法被截图的原因是其上的WebGL context的preserveDrawingBuffer为false,结合告警信息中的提示,那我们只需要将其设置为true,应该就可以解决,在Stack Overflow也有相关的解决方法,大家有兴趣的话可以看看: Canvas toDataURL() returns blank image

解决

在我们地图实例化的后面,增加一个立即执行函数,在函数里面将preserveDrawingBuffer属性值设置为true即可,如下:

// 解决domtoimage,html2canvas截图空白问题
HTMLCanvasElement.prototype.getContext = (function (origFn) {
  return function (type, attributes) {
    if (type.indexOf('webgl') > -1) {
      attributes = Object.assign({}, attributes, {
        preserveDrawingBuffer: true
      })
    }
    return origFn.call(this, type, attributes)
  }
})(HTMLCanvasElement.prototype.getContext)
posted @ 2024-07-03 14:28  ZerlinM  阅读(4)  评论(0编辑  收藏  举报