Fix: Implement frame resizing logic

This commit is contained in:
2026-03-20 23:20:36 -07:00
parent f456e46a15
commit 86f82677c9

View File

@@ -18,15 +18,27 @@ function loadImage(src) {
}); });
} }
export async function assembleGif(frames, fps) { export async function assembleGif(frames, fps, maxSize) {
if (!frames?.length) throw new Error('No frames to assemble.'); if (!frames?.length) throw new Error('No frames to assemble.');
if (!window.GIF) throw new Error('GIF.js not loaded.'); if (!window.GIF) throw new Error('GIF.js not loaded.');
const workerScript = await getWorkerUrl(); const workerScript = await getWorkerUrl();
const images = await Promise.all(frames.map(loadImage)); const images = await Promise.all(frames.map(loadImage));
const w = images[0].naturalWidth; let w = images[0].naturalWidth;
const h = images[0].naturalHeight; let h = images[0].naturalHeight;
// Resizing logic to cap the longest side
if (maxSize && (w > maxSize || h > maxSize)) {
if (w > h) {
h = Math.round((h * maxSize) / w);
w = maxSize;
} else {
w = Math.round((w * maxSize) / h);
h = maxSize;
}
}
const delay = Math.round(1000 / fps); const delay = Math.round(1000 / fps);
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
@@ -49,6 +61,7 @@ export async function assembleGif(frames, fps) {
ctx.clearRect(0, 0, w, h); ctx.clearRect(0, 0, w, h);
ctx.fillStyle = '#ffffff'; ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, w, h); ctx.fillRect(0, 0, w, h);
// Draw image scaled to the canvas dimensions
ctx.drawImage(image, 0, 0, w, h); ctx.drawImage(image, 0, 0, w, h);
gif.addFrame(ctx, { copy: true, delay }); gif.addFrame(ctx, { copy: true, delay });
} }