Animated GIF-GIF动画
知识要点
- (主要)使用GIF动画作为图标进行可视化,官方推荐借助Gifler库实现。
- (次要)map.on(‘pointermove’, function (e) {});可以改变鼠标经过gif图标时的光标样式,详见源码。
官网原文及译文
Example of using an animated GIF as an icon. Animation is achieved using the Gifler library.
使用GIF动画作为图标的例子。动画是使用Gifler库实现的。
源码
<!DOCTYPE html>
<html lang="zn">
<head>
<meta charset="UTF-8">
<!-- 引入OpenLayers CSS样式 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.13.0/css/ol.css"
type="text/css">
<!-- 引入OpenLayers JS库 -->
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.13.0/build/ol.js"></script>
<!-- 引入Gifler JS库 -->
<script src="https://unpkg.com/gifler@0.1.0/gifler.min.js"></script>
<!-- css代码 -->
<style>
.map {
width: 100%;
height: 400px;
}
</style>
<title>Animated GIF GIF动画</title>
</head>
<body>
<!-- html代码 -->
<div id="map" class="map"></div>
<!-- script代码 -->
<script>
// 定义一个点
const iconFeature = new ol.Feature({
geometry: new ol.geom.Point([0, 0]),
});
// 定义一个点的矢量资源
const vectorSource = new ol.source.Vector({
features: [iconFeature],
});
// 定义一个点的矢量图层
const vectorLayer = new ol.layer.Vector({
source: vectorSource,
});
// 定义光栅图层
const rasterLayer = new ol.layer.Tile({
source: new ol.source.Stamen({
layer: 'toner',
}),
});
// 初始化地图
const map = new ol.Map({
// 将光栅图层、一个点的矢量图层添加到地图中
layers: [rasterLayer, vectorLayer],
// 绑定页面元素
target: document.getElementById('map'),
// 设置视图
view: new ol.View({
center: [0, 0],
zoom: 2,
}),
});
// gif动图的url的链接
const gifUrl = 'https://openlayers.org/en/latest/examples/data/globe.gif';
// 使用Gifler将链接转化为gif图片
const gif = gifler(gifUrl);
// gif图片按刷新
gif.frames(
document.createElement('canvas'),
function (ctx, frame) {
if (!iconFeature.getStyle()) {
iconFeature.setStyle(
new ol.style.Style({
image: new ol.style.Icon({
img: ctx.canvas,
imgSize: [frame.width, frame.height],
opacity: 0.8,
}),
})
);
}
ctx.clearRect(0, 0, frame.width, frame.height);
ctx.drawImage(frame.buffer, frame.x, frame.y);
map.render();
},
true
);
// 改变鼠标经过gif图标时的光标样式为pointer
map.on('pointermove', function (e) {
const pixel = map.getEventPixel(e.originalEvent);
const hit = map.hasFeatureAtPixel(pixel);
map.getTarget().style.cursor = hit ? 'pointer' : '';
});
</script>
</body>
</html>