Skip to content

Instantly share code, notes, and snippets.

@xiangrenya
Last active May 6, 2021 02:18
Show Gist options
  • Save xiangrenya/53df5d6d76c1bedfa29c07dc4416db38 to your computer and use it in GitHub Desktop.
Save xiangrenya/53df5d6d76c1bedfa29c07dc4416db38 to your computer and use it in GitHub Desktop.
地图相关
function extractPartOfImage(img, { x, y, width, height }) {
const dpi = 2;
const el = document.createElement("canvas");
el.width = width * dpi;
el.height = height * dpi;
const ctx = el.getContext("2d");
ctx.drawImage(
img,
x * dpi,
y * dpi,
width * dpi,
height * dpi,
0,
0,
width * dpi,
height * dpi
);
return el.toDataURL();
}
function loadImage(url) {
const promise = new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = "Anonymous";
img.onload = () => resolve(img);
img.onerror = (e) => reject(e);
img.src = url;
});
return promise;
}
function loadJson(url) {
return fetch(url).then((res) => res.json());
}
function mapImageToDataURL(map, icon) {
if (!icon) {
return undefined;
}
const image = map.style.imageManager.images[icon];
if (!image) {
return undefined;
}
const canvasEl = document.createElement("canvas");
canvasEl.width = image.data.width;
canvasEl.height = image.data.height;
const ctx = canvasEl.getContext("2d");
ctx.putImageData(
new ImageData(
Uint8ClampedArray.from(image.data.data),
image.data.width,
image.data.height
),
0,
0
);
// Not toBlob() because toDataURL is faster and synchronous.
return canvasEl.toDataURL();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment