react 之 openlayer地图图片下载
一、原理
地图渲染是通过canvas来渲染出来的,openlayers提供的map.once('postcompose', function (event) {})函数可以获取canvas对象,将canvas转化成图片下载下来,便可实现。
二、引入所依赖的文件
import React, { Component } from 'react';import Map from '../../component/map/map';
import { Button } from 'antd';
import style from './map.css';
三、加载地图组件和页面的渲染
render() { return (
<div className={style.mapBg}>
<Button type="primary" style={{ marginLeft: '10px' }} onClick={this.savePng}>
导出png
</Button>
<Map ref="map" center={{ lon: 113.8, lat: 34.6 }} />;
</div>
);
}
四、canvas转化成图片和图片的下载
var canvas = event.context.canvas var MIME_TYPE = "image/png";
var imgURL = canvas.toDataURL(MIME_TYPE);
var dlLink = document.createElement('a');
dlLink.download = 'map.png';
dlLink.href = imgURL;
dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');
document.body.appendChild(dlLink);
dlLink.click();
document.body.removeChild(dlLink);
});
map.renderSync();
五、全部代码
// 设置地图背景色import React, { Component } from 'react';
import Map from '../../component/map/map';
import { Button } from 'antd';
import style from './map.css';
class MapOverviewMap extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
// console.log(bg)
}
// 地图保存成png
savePng =()=>{
let {map} = this.refs.map
let that = this
// 实现canvas转化成图片
map.once('postcompose', function (event) {
var canvas = event.context.canvas;
var MIME_TYPE = "image/png";
var imgURL = canvas.toDataURL(MIME_TYPE);
var dlLink = document.createElement('a');
dlLink.download = 'map.png';
dlLink.href = imgURL;
dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');
document.body.appendChild(dlLink);
dlLink.click();
document.body.removeChild(dlLink);
});
map.renderSync();
}
render() {
return (
<div className={style.mapBg}>
<Button type="primary" style={{ marginLeft: '10px' }} onClick={this.savePng}>
导出png
</Button>
<Map ref="map" center={{ lon: 113.8, lat: 34.6 }} />;
</div>
);
}
}
export default MapOverviewMap;
六、效果
以上是 react 之 openlayer地图图片下载 的全部内容, 来源链接: utcz.com/z/384117.html