经纬志
首页 / MapLibre / API 文档

CanvasSource

先看结论

把 canvas 的像素当作地图图层,逐帧绘制的雷达、粒子与热区都能直接贴到地理坐标上。

最后验证 2026-11-03 · MapLibre GL JS 4.x · 更新 2026-10-28 · 引用本文
map.addSource(id, { type: 'canvas', canvas: 'canvas-id', coordinates: [四点], animate: true })

参数

字段默认说明
canvas—canvas 元素的 id 或元素本身,必填
coordinates—左上、右上、右下、左下四角经纬度
animatetrue为 true 时每帧读取 canvas,画面随绘制更新

animate 默认开启,意味着 canvas 内容一变地图就会重绘。 静态内容可以设为 false,只读一次,省掉持续的纹理上传。

成员

成员说明
getCanvas()取回与该源绑定的 canvas 元素
setCoordinates(coordinates)改变覆盖的地理范围
data 事件首帧读取完成
error 事件canvas 尺寸为零或元素不存在

示例

var canvas = document.createElement('canvas');
canvas.width = 512;
canvas.height = 512;
var ctx = canvas.getContext('2d');

function draw(t) {
  ctx.clearRect(0, 0, 512, 512);
  ctx.fillStyle = 'rgba(31, 95, 208, 0.25)';
  ctx.beginPath();
  ctx.arc(256, 256, 120 + 40 * Math.sin(t / 600), 0, Math.PI * 2);
  ctx.fill();
  requestAnimationFrame(draw);
}
requestAnimationFrame(draw);

map.addSource('radar', {
  type: 'canvas',
  canvas: canvas,
  coordinates: [
    [116.0, 40.1],
    [116.7, 40.1],
    [116.7, 39.7],
    [116.0, 39.7]
  ],
  animate: true
});

map.addLayer({
  id: 'radar',
  type: 'raster',
  source: 'radar',
  paint: { 'raster-opacity': 0.8, 'raster-fade-duration': 0 }
});

注意事项

canvas 每帧重绘时,纹理上传的开销与像素面积成正比。 512×512 在桌面端基本无感,1024×1024 以上且 60 帧刷新就会明显掉帧, 能减到 30 帧就减。

canvas 必须在 DOM 或至少可绘制。未插入文档的 canvas 也能出图,但宽高为 0 时上传会失败,只在控制台留下一条尺寸错误。 显式设置 width 与 height 可以避开。

引用本文

经纬志(2026)。《CanvasSource》。https://www.jingweizhi.com/maplibre/api/canvas-source.html(访问日期 2026-11-03)。