文章目录
- 一、前言
- 二、代码实现
- 三、总结
一、前言
本文基于OpenLayers3,canvas转图片实现地图导出图片的功能。
二、代码实现
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>导出PNG图片</title>
<link href="../../libs/ol3/ol.css" rel="stylesheet" type="text/css"/>
<script src="../../libs/ol3/ol.js" type="text/javascript"></script>
<script src="../../libs/other/FileSaver.min.js" type="text/javascript"></script>
<link href="../../css/style.css" rel="stylesheet" type="text/css"/>
<style>
#mapCon {
width: 100%;
height: 90%;
position: absolute;
}
</style>
</head>
<body>
<div class="ToolLib">
<input type="button" class="ButtonLib" id="export-png" value="下载 PNG"/>
</div>
<div id="map" title="地图显示" style="padding: 5px">
</div>
<script>
var tdttk = '****'; //天地图秘钥tk,官网注册申请
var TiandiMap_vec = new ol.layer.Tile({
title: "天地图矢量图层",
source: new ol.source.XYZ({
url: "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=" + tk,
wrapX: false,
crossOrigin: "Anonymous"
})
});
var Tianditu_cva = new ol.layer.Tile({
title: "天地图矢量注记图层",
source: new ol.source.XYZ({
url: "http://t0.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=" + tk,
wrapX: false,
crossOrigin: "Anonymous"
})
});
var map = new ol.Map({
layers: [TiandiMap_vec, Tianditu_cva,
new ol.layer.Vector({
source: new ol.source.Vector({
url: "../../data/geojson/countries.geojson",
format: new ol.format.GeoJSON()
})
})
],
target: 'map',
controls: ol.control.defaults({
attributionOptions: ({
collapsible: false
})
}),
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
document.getElementById('export-png').addEventListener('click', function () {
map.once('postcompose', function (event) {
var canvas = event.context.canvas;
canvas.toBlob(function (blob) {
saveAs(blob, 'map.png');
});
});
map.renderSync();
});
</script>
</body>
</html>
三、总结
以上为基于openlayer3 实现导出图片的简单案例,希望对您有帮助~