一、mapboxgl可以添加png或者jpg类型的图片到雪碧图中
async function addPng(id, url) {
const img = await new Promise((resolve) => {
map.loadImage(url, (error, image) => {
if (error) throw error;
resolve(image);
});
});
if (!map.hasImage(id)) {
map.addImage(id, img);
}
}
二、mapboxgl不支持直接添加svg到雪碧图,可以先把svg转成base64,再绘制到canvas上生成一张图片
直接添加报错:mapbox-gl.js:31 Uncaught (in promise) Error: Could not load image because of The source image could not be decoded.. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.
at mapbox-gl.js:31:14115
async function addSvg(id, url) {
const img = await new Promise(async (resolve) => {
let res = await axios.get(url);
let objE = document.createElement("div");
objE.innerHTML = res.data;
// 设置svg的颜色,非必须
let d = objE.children[0];
let color = '#f00';
d.style.fill = color;
d.querySelectorAll("path").forEach((item) =>
item.setAttributeNS(null, "fill", color)
);
let image = new Image();
image.src =
"data:image/svg+xml;base64," +
window.btoa(unescape(encodeURIComponent(objE.innerHTML)));
let canvas = document.createElement("canvas"); //准备空画布
canvas.width = 20;
canvas.height = 20;
let context = canvas.getContext("2d"); //取得画布的2d绘图上下文
image.onload = function () {
context.drawImage(image, 0, 0, 20, 20);
let outImg = new Image();
outImg.src = canvas.toDataURL("image/webp");
resolve(outImg);
};
});
if (!map.hasImage(id)) {
map.addImage(id, img);
}
}