html2canvas 捕获除内部画布内容之外的所有内容

And*_*lko 3 javascript webgl html2canvas leaflet

我有一张通过leaflet.

我需要使用html2canvas.

为了使用html2canvas,我需要提供一个 DOM 元素来捕获 ( elementToCapture) 和一个可选的配置 ( html2canvasConfiguration)。

var html2canvasConfiguration = {
    useCORS: true,
    width: map._size.x,
    height: map._size.y,
    backgroundColor: null,
    logging: true,
    imageTimeout: 0
};

var elementToCapture = map._container.getElementsByClassName('leaflet-pane leaflet-map-pane')[0];
html2canvas(elementToCapture, html2canvasConfiguration).then(function (canvas) {
    var link = document.createElement('a');
    link.download = 'test.png';
    link.href = canvas.toDataURL();
    link.click();
    link.remove();
})
Run Code Online (Sandbox Code Playgroud)

我按leaflet-pane leaflet-map-pane类提取一个元素,它基本上代表整个地图,包括控件(放大/缩小按钮、比例等)、自定义标记、工具提示、叠加层、弹出窗口。

整个 DOM 看起来像

<div class="leaflet-pane leaflet-map-pane">
    <div class="leaflet-pane leaflet-tile-pane">
        <div class="leaflet-gl-layer mapboxgl-map">
            <div class="mapboxgl-canvas-container">
                <canvas class="mapboxgl-canvas leaflet-image-layer leaflet-zoom-animated"></canvas>
            </div>
            <div class="mapboxgl-control-container"></div>
        </div>
    </div>
    <div class="leaflet-pane leaflet-shadow-pane"></div>
    <div class="leaflet-pane leaflet-overlay-pane"></div>
    <div class="leaflet-pane leaflet-marker-pane"></div>
    <div class="leaflet-pane leaflet-tooltip-pane"></div>
    <div class="leaflet-pane leaflet-popup-pane"></div>
<div class="leaflet-control-container"></div>
Run Code Online (Sandbox Code Playgroud)

我面临的问题是leaflet-pane leaflet-tile-pane元素(特别是内部的内容canvas)没有被html2canvas. 简单来说,我在地图上看到了一切,但我没有看到地图本身。

在此处输入图片说明

在此处输入图片说明

更新1:

我目前使用的版本是1.0.0-rc.1(最新的)。

更新 2:

画布的性质是webgl。可能是这个问题吗?根据这个,他们做支撑webgl油画。

更新 3:

我试图以编程方式获取画布并调用toDataURL它。它导致了一个空白的屏幕截图,即使有preserveDrawingBuffer黑客攻击也是如此。

更新 4:

奇怪的是,它不仅仅捕捉某些画布。我创建了一个2d画布(通过添加preferCanvas到地图配置)并显示出来。

gma*_*man 6

试试这个,将它添加到页面顶部,在任何其他脚本之前

<script>
HTMLCanvasElement.prototype.getContext = function(origFn) {
  return function(type, attribs) {
    attribs = attribs || {};
    attribs.preserveDrawingBuffer = true;
    return origFn.call(this, type, attribs);
  };
}(HTMLCanvasElement.prototype.getContext);
</script>
Run Code Online (Sandbox Code Playgroud)

它有帮助吗?

  • 我想吻你:) 你能详细说明一下它为什么有效吗?它是否强制“html2canvas”在每次检索画布上下文时设置“preserveDrawingBuffer”? (3认同)