d2/lib/png/generate_png.js

48 lines
1.4 KiB
JavaScript
Raw Normal View History

2023-04-13 20:40:58 +00:00
async ({ imgString, scale }) => {
2022-11-17 01:41:53 +00:00
const tempImg = new Image();
const loadImage = () => {
return new Promise((resolve, reject) => {
tempImg.onload = (event) => resolve(event.currentTarget);
tempImg.onerror = () => {
2023-04-11 17:38:44 +00:00
reject("error loading string as an image:\n" + imgString);
2022-11-17 01:41:53 +00:00
};
tempImg.src = imgString;
});
};
const img = await loadImage();
const canvas = document.createElement("canvas");
2023-04-11 17:38:44 +00:00
canvas.width = img.width * scale;
canvas.height = img.height * scale;
2023-04-13 20:40:58 +00:00
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas
const MAX_DIMENSION = 32767;
const MAX_AREA = 268435456;
const ratio = img.width / img.height;
if (ratio > 1) {
if (canvas.width > MAX_DIMENSION) {
canvas.width = MAX_DIMENSION;
canvas.height = MAX_DIMENSION / ratio;
}
} else {
if (canvas.height > MAX_DIMENSION) {
canvas.height = MAX_DIMENSION;
canvas.width = MAX_DIMENSION * ratio;
}
}
const currentArea = canvas.width * canvas.height;
if (currentArea > MAX_AREA) {
const areaRatio = MAX_AREA / currentArea;
canvas.height = Math.floor(canvas.height * areaRatio);
canvas.width = Math.floor(canvas.width * areaRatio);
}
2022-11-17 01:41:53 +00:00
const ctx = canvas.getContext("2d");
if (!ctx) {
2022-11-18 03:02:25 +00:00
return new Error("could not get canvas context");
2022-11-17 01:41:53 +00:00
}
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL("image/png");
}