添加生成的图像
向地图添加程序生成的图像;
<!DOCTYPE html>
<html lang="en">
<head>
<title>添加生成的图像</title>
<meta property="og:description" content="向地图添加程序生成的图像" />
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel='stylesheet' href='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.css' />
<script src='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.js'></script>
<style>
body { margin: 0; padding: 0; }
html, body, #map { height: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
const map = new maplibregl.Map({
container: 'map',
style:
'https://demotiles.maplibre.org/styles/osm-bright-gl-style/style.json',
center: [0, 0],
zoom: 1
});
// 创建一个20px x 20px的Canvas元素作为图像源
const createCanvas = () => {
const canvas = document.createElement('canvas');
canvas.width = 20;
canvas.height = 20;
const context = canvas.getContext('2d');
// 创建一个红色的点,其中心为透明
// 此方法使用原生Canvas 2D API
// 可以替换为任何使用Canvas的渲染逻辑
// 例如使用HTML Canvas 2D Context, WebGL, WebGPU或其他JavaScript库
// https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D
context.fillStyle = 'rgba(255, 0, 0, 1)';
context.beginPath();
context.arc(10, 10, 8, 0, Math.PI * 2);
context.fill();
context.strokeStyle = 'white';
context.lineWidth = 3;
context.stroke();
// 绘制内部透明区域
context.globalCompositeOperation = 'destination-out';
context.beginPath();
context.arc(10, 10, 5, 0, Math.PI * 2);
context.fill();
return canvas;
};
map.on('load', () => {
// 添加Canvas为图像源
const canvas = createCanvas();
map.addImage('canvas-image', canvas);
map.addSource('points', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [0, 0]
},
'properties': {
'title': '赤道上的一点'
}
}
]
}
});
map.addLayer({
'id': 'points',
'type': 'symbol',
'source': 'points',
'layout': {
'icon-image': 'canvas-image',
'icon-allow-overlap': true
}
});
});
</script>
</body>
</html>