经纬志
首页 / MapLibre / API 文档

addImage

先看结论

把图片注册到样式的图标表,之后 icon-image 就能按 id 引用它。

最后验证 2026-11-03 · MapLibre GL JS 4.x · 更新 2026-10-29 · 引用本文
map.addImage(id, image, options?) → this

参数

参数类型说明
idstring图标名,供 icon-image 引用
imageHTMLImageElement | ImageData | ImageBitmap | StyleImageInterface位图,或实现动态图像接口的对象
options.pixelRationumber图像像素与屏幕像素的比例,@2x 图传 2
options.sdfboolean是否为有向距离场图,为真时可用 icon-color 改色
options.stretchX / options.stretchY[number, number][]可拉伸区域,用于文字气泡自适应宽度
options.content[number, number, number, number]九宫格中不参与拉伸的内容区域

用 Canvas 生成图标

function makeDot(color, size) {
  var canvas = document.createElement('canvas');
  canvas.width = canvas.height = size;

  var ctx = canvas.getContext('2d');
  ctx.beginPath();
  ctx.arc(size / 2, size / 2, size / 2 - 1, 0, Math.PI * 2);
  ctx.fillStyle = color;
  ctx.fill();

  return canvas;
}

map.addImage('dot-blue', makeDot('#1f5fd0', 32), { pixelRatio: 2 });

map.addLayer({
  id: 'poi-dot',
  type: 'symbol',
  source: 'poi',
  layout: {
    'icon-image': 'dot-blue',
    'icon-size': 1,
    'icon-allow-overlap': true
  }
});

pixelRatio: 2 表示图像按两倍像素绘制, 显示尺寸是原图的一半,在高分屏上不发虚。

SDF 图标改色

map.addImage('pin-sdf', pinImageData, { sdf: true });

map.addLayer({
  id: 'pin',
  type: 'symbol',
  source: 'poi',
  layout: { 'icon-image': 'pin-sdf', 'icon-size': 0.8 },
  paint: { 'icon-color': '#e0552f' }
});

普通图片设置 icon-color 没有效果,只有 SDF 图才能按颜色渲染。 SDF 需要离线预处理生成,不能把普通 PNG 直接标记为 sdf: true。

动态图像

第三个参数也可以传实现 StyleImageInterface 的对象, 由 render 方法每帧更新像素。逐帧动画的写法见该接口的页面。

替换与移除

操作方法
更新已有图标map.updateImage(id, image),数据量小时开销低
删除图标map.removeImage(id)
查询是否存在map.hasImage(id)

重复使用同一个 id 前先 hasImage 判断,或直接改成 updateImage,避免图标表里残留旧数据。

图标要在样式加载完成后添加。 setStyle 会清空自定义图标,切换主题后需要重新 addImage。把注册逻辑放在 style.load 回调里最稳。

引用本文

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