Created
September 9, 2024 04:06
-
-
Save Ebrahim-Ramadan/0c6eddab446d9caabf934b59cf2504e7 to your computer and use it in GitHub Desktop.
Clipboard API's limited support for image formats. As of now, it primarily supports PNG and JPEG formats, so we make sure you properly handle the canvas.toBlob() method to update the pngBlob. Ensure that the clipboard write operation supports PNG format after conversion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const copyToClipboard = async (dataUrl: string) => { | |
try { | |
// Convert the Data URL to a Blob | |
const response = await fetch(dataUrl); | |
const blob = await response.blob(); | |
// Check if the image is in a supported format, convert if necessary | |
let pngBlob = blob; | |
if (blob.type !== 'image/png') { | |
// Convert to PNG if necessary | |
const img = new Image(); | |
img.src = URL.createObjectURL(blob); | |
await new Promise<void>((resolve) => { | |
img.onload = () => resolve(); | |
}); | |
const canvas = document.createElement('canvas'); | |
canvas.width = img.width; | |
canvas.height = img.height; | |
const ctx = canvas.getContext('2d'); | |
if (ctx) { | |
ctx.drawImage(img, 0, 0); | |
// Convert the image to PNG Blob | |
pngBlob = await new Promise<Blob | null>((resolve) => { | |
canvas.toBlob((blob) => { | |
resolve(blob); | |
}, 'image/png'); | |
}); | |
if (!pngBlob) { | |
throw new Error("Failed to convert image to PNG format."); | |
} | |
} | |
} | |
// Create a ClipboardItem with the Blob | |
const clipboardItem = new ClipboardItem({ [pngBlob.type]: pngBlob }); | |
// Write the ClipboardItem to the clipboard | |
await navigator.clipboard.write([clipboardItem]); | |
console.log("Image copied to clipboard"); | |
} catch (err) { | |
console.error("Failed to copy image: ", err); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment