許多新式瀏覽器都支援將圖片複製到剪貼簿 (格式為 PNG 和 SVG)。基於安全考量,目前仍不支援其他格式。
新穎時尚
使用 Async Clipboard API
Clipboard.write()
方法會採用 ClipboardItem
物件的陣列,並傳回 Promise,以便在圖片成功寫入剪貼簿時解析。Clipboard.write()
只能透過有焦點的 window
物件使用。
經典風格
使用了 navigator.clipboard.writeText()
雖然並非所有瀏覽器都支援 navigator.clipboard.write()
二進位資料,但這些瀏覽器都支援 navigator.clipboard.writeText()
。如果您想複製 SVG 圖片,可以複製 SVG 原始碼,而非直接複製圖片。很抱歉,如果是 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;
}
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);
}
});