将版权信息文本直接打印到OpenLayers画布中
我需要在我的openlayers地图中添加一些版权信息文本。该网站提供了一个按钮,以类似的方式将地图导出为PNG,如所示,版权文本也必须位于导出的PNG地图上 因此,我不能对版权文本使用html覆盖,但必须将文本直接打印到画布中,因为“将地图导出到PNG”功能只用于导出画布中的内容(没有html控件或html覆盖) 我尝试了两种方法。两者都不起作用;)将版权信息文本直接打印到OpenLayers画布中,openlayers,openlayers-3,Openlayers,Openlayers 3,我需要在我的openlayers地图中添加一些版权信息文本。该网站提供了一个按钮,以类似的方式将地图导出为PNG,如所示,版权文本也必须位于导出的PNG地图上 因此,我不能对版权文本使用html覆盖,但必须将文本直接打印到画布中,因为“将地图导出到PNG”功能只用于导出画布中的内容(没有html控件或html覆盖) 我尝试了两种方法。两者都不起作用;) 使用ol.source.ImageCanvas,如图所示。问题是当放大或缩小时,文本会跳跃。但是文本应该是静态的 在OpenLayers初始化后
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.fillText('© My Copyright Text'), 500, 600);
这张照片什么都没有,我也不知道为什么。在“写入”openlayers画布时有什么特别的地方吗
那么,向地图画布添加一些简单文本的最佳方法是什么呢?您可以使用
ol.Overlay
来实现以下目的:
©我的版权文本
即使在缩放时也应静态定位
您可以使用地图的postdrender
事件,获取地图画布,并根据您的想法对其进行修改。在中,已注册了postdrender
侦听器,因此您可以轻松地修改它以添加属性文本,例如
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');
});
});
我创建了一个工作的JSFIDLE,代码如下:,另一个答案是:不。这会将文本添加为html,因此无法导出为PNG。有一个属性,当您单击“下载PNG”时,您将看到PNG与画布中的完全相同-所有html覆盖都从PNG中删除。我需要关于导出的PNG的版权信息。谢谢你的回答。我看到了一个轻微的冲突——您首先编写时使用了
postrend
,但在代码中使用了postcompose
。使用哪个事件?在我看来,查看OL源代码时,似乎postcompose
与画布渲染的关系更为密切。
<div id="map"></div>
<div style="display: none;">
<div id="copyright">
© My Copyright text
<br>
Should be statically positioned even when zooming
</div>
</div>
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');
});
});