कई आधुनिक ब्राउज़र, इमेज को क्लिपबोर्ड पर PNG और SVG फ़ॉर्मैट में कॉपी करने की सुविधा देते हैं. सुरक्षा कारणों से, फ़िलहाल अन्य फ़ॉर्मैट इस्तेमाल नहीं किए जा सकते.
मॉडर्न तरीका
Async Clipboard API का इस्तेमाल करना
Clipboard.write() वाला तरीका, ClipboardItem ऑब्जेक्ट का कलेक्शन लेता है. साथ ही, यह एक ऐसा Promise दिखाता है जो इमेज को क्लिपबोर्ड पर सेव होने के बाद पूरा होता है. Clipboard.write() का इस्तेमाल सिर्फ़ उस window ऑब्जेक्ट से किया जा सकता है जिस पर फ़ोकस किया गया है.
क्लासिक तरीका
navigator.clipboard.writeText() का इस्तेमाल करना
हालांकि, फ़िलहाल सभी ब्राउज़र बाइनरी डेटा के लिए navigator.clipboard.write() का इस्तेमाल नहीं करते हैं. हालांकि, वे सभी navigator.clipboard.writeText() का इस्तेमाल करते हैं. अगर आपको एसवीजी इमेज कॉपी करनी है, तो इमेज को कॉपी करने के बजाय, एसवीजी सोर्स कोड को कॉपी किया जा सकता है. माफ़ करें, PNG इमेज के लिए यह सुविधा उपलब्ध नहीं है.
परतदार वृद्धि
const button = document.querySelector('button');
const img = document.querySelector('img');
button.addEventListener('click', async () => {
const responsePromise = fetch(img.src);
try {
if ('write' in navigator.clipboard) {
await navigator.clipboard.write([
new ClipboardItem({
'image/svg+xml': new Promise(async (resolve) => {
const blob = await responsePromise.then(response => response.blob());
resolve(blob);
}),
}),
]);
// Image copied as image.
} else {
const text = await responsePromise.then(response => response.text());
await navigator.clipboard.writeText(text);
// Image copied as source code.
}
} catch (err) {
console.error(err.name, err.message);
}
});
इस बारे में और पढ़ें
डेमो
एचटीएमएल
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="icon"
href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎉</text></svg>"
/>
<title>How to copy images</title>
</head>
<body>
<h1>How to copy images</h1>
<img src="assets/fugu.svg" alt="Fugu fish." width="128" height="128">
<button type="button">Copy</button>
</body>
</html>सीएसएस
:root {
color-scheme: dark light;
}
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
margin: 1rem;
font-family: system-ui, sans-serif;
}
button {
display: block;
}
JS
const button = document.querySelector('button');
const img = document.querySelector('img');
button.addEventListener('click', async () => {
const responsePromise = fetch(img.src);
try {
if ('write' in navigator.clipboard) {
await navigator.clipboard.write([
new ClipboardItem({
'image/svg+xml': new Promise(async (resolve) => {
const blob = await responsePromise.then(response => response.blob());
resolve(blob);
}),
}),
]);
// Image copied as image.
} else {
const text = await responsePromise.then(response => response.text());
await navigator.clipboard.writeText(text);
// Image copied as source code.
}
} catch (err) {
console.error(err.name, err.message);
}
});