解决Openlayers地图无法转图片的问题
如果canvas转换的过程中出现画布污染,请及时检查加载图层的方式,
错误信息如下:Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported
简单粗暴的方式,只要是加载关于图片的都把跨域设置一下即可crossOrigin: “anonymous”
加载瓦片图层
import TileLayer from "ol/layer/Tile";
import {XYZ} from "ol/source";
new TileLayer({
source: new XYZ({
url: url,
wrapX: true,
crossOrigin: "anonymous",
...sourceOptions
}),
...tileLayerOptions
});
加载icon
import {Icon} from "ol/style";
new Icon({
src: iconName,
width: iconSize,
height: iconSize,
crossOrigin: "anonymous",
});
地图转图片
map.render(); // 建议最好是转换图片的时候对地图重新渲染一下,防止生成的图片为空白或其他问题。
const canvas = map.targetElement_.querySelector('canvas');
const imgUrl = canvas.toDataURL();
console.log(imgUrl);
完结,撒花✿✿ヽ(°▽°)ノ✿