Skip to content

Commit

Permalink
fix(lightbox): copy all image formats to png (#245)
Browse files Browse the repository at this point in the history
  • Loading branch information
domw30 authored Dec 2, 2024
1 parent ea479af commit e351cc9
Showing 1 changed file with 32 additions and 46 deletions.
78 changes: 32 additions & 46 deletions src/components/Lightbox/Lightbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,53 +36,39 @@ export const Lightbox = ({ items, startingIndex = 0, onClose, provider }: Lightb
if (!currentItem?.url) return;

try {
const response = await fetch(currentItem.url);
const blob = await response.blob();

try {
await navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob
})
]);
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
} catch (writeError) {
// Fallback to canvas method
const img = new Image();
img.crossOrigin = 'anonymous';

await new Promise((resolve, reject) => {
img.onload = resolve;
img.onerror = reject;
img.src = currentItem.url;
});

const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;

const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('Failed to get canvas context');

ctx.drawImage(img, 0, 0);

canvas.toBlob(async blob => {
if (blob) {
try {
await navigator.clipboard.write([
new ClipboardItem({
'image/png': blob
})
]);
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
} catch (clipboardError) {
console.error('Failed to write to clipboard:', clipboardError);
}
const img = new Image();
img.crossOrigin = 'anonymous';

await new Promise((resolve, reject) => {
img.onload = resolve;
img.onerror = reject;
img.src = currentItem.url;
});

const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;

const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('Failed to get canvas context');

ctx.drawImage(img, 0, 0);

canvas.toBlob(async blob => {
if (blob) {
try {
await navigator.clipboard.write([
new ClipboardItem({
'image/png': blob
})
]);
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
} catch (clipboardError) {
console.error('Failed to write to clipboard:', clipboardError);
}
}, 'image/png');
}
}
}, 'image/png');
} catch (err) {
console.error('Failed to copy image:', err);
}
Expand Down

0 comments on commit e351cc9

Please sign in to comment.