在OpenLayers示例中调用domtoimage.toPng()时出现“ SecurityError:此操作不安全”

时间:2019-12-22 07:17:36

标签: javascript django dom openlayers

我目前正在添加功能,以将OpenLayers Map转换为png文件(示例为here)。但是,在以下代码中调用domtoimage.toPng()时,Firefox(Ubuntu版本68.0.2)给我错误SecurityError: This operation is insecure。我已经检查了所有地方,而dom-to-image库似乎没有其他人遇到这个问题,因此我被困在如何解决此错误的问题上。我用于Map的JavaScript代码与示例中给出的代码非常相似,并在此处给出:

<script type="text/javascript">

var extent = [0, 0, 3000, 4213];
var projection = new ol.proj.Projection({
    code: 'my-image',
    units: 'pixels',
    extent: extent,
});
var map = new ol.Map({
    controls: ol.control.defaults().extend([
        new ol.control.FullScreen()
    ]),
    layers: [
        new ol.layer.Image({
            source: new ol.source.ImageStatic({
                attributions: 'My Image Attributions',
                url: "{{record | img_url}}", // Django stuff defined earlier
                projection: projection,
                imageExtent: extent
            })
        })
    ],
    target: 'map', 
    view: new ol.View({ 
        projection: projection,
        center: ol.extent.getCenter(extent),
        zoom: 2, 
        maxZoom: 8
    })
});

map.addOverlay(new ol.Overlay({
    position: [0, 0],
    element: document.getElementById('null')
}));


// export options for dom-to-image.
var exportOptions = {
    filter: function(element) {
        return element.className ? element.className.indexOf('ol-control') === -1 : true;
    }
};

document.getElementById('export-png').addEventListener('click', function() {
    map.once('rendercomplete', function() {
        domtoimage.toPng(map.getTargetElement(), exportOptions)
            .then(function(dataURL) {
                var link = document.getElementById('image-download');
                link.href = dataURL;
                link.click();
            });
    });
    map.renderSync();
});

HTML实际上与示例中的相同,因此我认为问题出在这里。也许在地图中使用StaticImage会有所帮助?还是通过Django框架以某种未知的方式进行篡改?我不太确定,对解决此问题的任何诊断/帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我认为应该有这样的东西

new ol.layer.Tile({
    name: 'name',
    source: new ol.source.TileWMS({
        ...
        crossOrigin: 'anonymous' // <-- Add this to the json.
    })
})
  

了解详情:

     

https://openlayers.org/en/v4.6.5/apidoc/ol.source.ImageWMS.html   https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image