跳到主要内容
版本:9.1.1

动态图标

利用Canvas API构建动态点图标

show
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>动态图标</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<script src='https://delivery.mapmost.com/cdn/sdk/webgl/v9.1.1/mapmost-webgl-min.js'></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>

<script>
const map = new mapmost.Map({
container: 'map',
style: '<your style url>',
center: [120.72862794279075, 31.326409968777853],
zoom: 10,
userId: '***', // 授权码
});

const size = 200;

// 定义颜色变量
const color = '#297F87'
const rgba1 = `rgba(61, 243, 245,`
const pulsingDot = {
width: size,
height: size,
data: new Uint8Array(size * size * 4),

// 获取绘制地图的canvas
onAdd: function () {
const canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;
this.context = canvas.getContext('2d');
},

// 在渲染的每一帧刷新一次图标
render: function () {
const duration = 1000;
const t = (performance.now() % duration) / duration;

const radius = (size / 2) * 0.2;
const outerRadius = (size / 2) * 0.5 * t + radius;
const context = this.context;

// 绘制圆点的外层扩散波纹
context.clearRect(0, 0, this.width, this.height);
context.beginPath();
context.arc(
this.width / 2,
this.height / 2,
outerRadius,
0,
Math.PI * 2
);
context.fillStyle = rgba1 + `${(0.7- t)<0?0:(0.7- t)})`;
context.fill();

// 绘制中心圆点
context.beginPath();
context.arc(
this.width / 2,
this.height / 2,
radius,
0,
Math.PI * 2
);
context.fillStyle = color;
context.fill();

// 更新动态图片的数据
this.data = context.getImageData(
0,
0,
this.width,
this.height
).data;

// 不断地重绘地图,使点拥有平滑的动画
map.triggerRepaint();

// 通知地图图片已更新
return true;
}
};

// 添加图层
map.on('load', () => {
map.addImage('pulsing-dot', pulsingDot, { pixelRatio: 2 });

map.addSource('dot-point', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [120.60077271290618, 31.31545402626199]
}
}
]
}
});
map.addLayer({
'id': 'symbol-layer',
'type': 'symbol',
'source': 'dot-point',
'layout': {
'icon-image': 'pulsing-dot'
}
});
});
</script>

</body>
</html>