2016-12-14 42 views
1

我需要向我的openlayers地圖添加一些版權信息文本。該網站提供了一個按照類似於http://openlayers.org/en/latest/examples/export-map.html所示的方式將地圖導出到PNG的按鈕。因此,導出的PNG地圖上的版權文本也必須處於打開狀態。因爲「Exported the map to PNG」東西適用於只輸出畫布中的內容(無html控件,或者,無法使用HTML控件),因此,我不能使用HTML疊加版本文本,但必須將文本直接打印到畫布上HTML覆蓋)。將版權信息文本直接打印到OpenLayers畫布中

我試過兩種方法。這兩個不工作;)

  1. 使用ol.source.ImageCanvas在這個jsfiddle所示。問題是當放大或縮小時,文本是。但文字應該是靜態的。

  2. 通過獲得的OpenLayers後的OpenLayers帆布已經初始化,然後使用這個帆布直接

下面是正在運行的OpenLayers已經盡了initilisation第二方法的代碼:在所有

var canvas = document.getElementById('canvas'); 
var context = canvas.getContext('2d'); 
context.fillText('© My Copyright Text'), 500, 600); 

這只是打印和什麼我不知道爲什麼。 「寫入」openlayers畫布時有什麼特別之處嗎?

那麼將一些簡單的文本添加到地圖畫布的最佳方法是什麼?

回答

3

您可以使用地圖的postrender事件,獲取地圖畫布上,並對其進行修改無論你在想什麼。在export-map.html example中,postrender聽衆已被註冊,因此您可以輕鬆修改它以添加歸因文本,例如,

map.once('postcompose', function(event) { 
    var canvas = event.context.canvas; 
    // Add attribution text 
    event.context.textAlign = 'right'; 
    event.context.fillText('© My Copyright Text', canvas.width - 5, canvas.height - 5); 
    // Now export the map 
    canvas.toBlob(function(blob) { 
    saveAs(blob, 'map.png'); 
    }); 
}); 

我創建了一個工作的jsfiddle與此代碼:https://jsfiddle.net/ahocevar/8c4knpu6/

+0

感謝您的回答。我看到一個小小的衝突 - 你首先寫了'postrender',但是在你的代碼中使用'postcompose'。哪一個事件是使用的?對我來說,看看OL的來源,看起來'postcompose'與畫布渲染關係更密切。 –

-1

您可以使用此一ol.Overlay

https://jsfiddle.net/x66v59wt/2/

var map = new ol.Map({ 
    layers: [ 
    new ol.layer.Tile({ 
     title: 'basemap', 
     source: new ol.source.Stamen({ layer: 'toner' }) 
    }) 
    ], 
    target: 'map', 
    view: new ol.View({ 
    center: ol.proj.fromLonLat([-97, 38]), 
    zoom: 4 
    }), 
    overlays: [ 
    new ol.Overlay({ 
     id: 'copyright', 
     element: document.getElementById('copyright'), 
     position: ol.proj.fromLonLat([-97, 38]) 
    }) 
    ] 
}); 

// If you want to text to be "pinned" to the map center, for example 
map.getView().on('change:center', function (e) { 
    map.getOverlayById('copyright').setPosition(this.getCenter()); 
}); 

...

<div id="map"></div> 
<div style="display: none;"> 
    <div id="copyright"> 
    © My Copyright text 
    <br> 
    Should be statically positioned even when zooming 
    </div> 
</div> 
+0

如對方回答:不。這將文本添加爲​​html,因此無法導出到PNG。 http://openlayers.org/en/latest/examples/export-map.html有一個屬性,當您點擊「下載PNG」時,您會看到PNG與Canvas中的相同 - 所有html疊加層將從PNG中刪除。我還需要導出的PNG上的版權信息。 – nachtigall