|
| 1 | +const copyButton = document.querySelector(".copy"); |
| 2 | +const pasteButton = document.querySelector(".paste"); |
| 3 | +const pre = document.querySelector("pre"); |
| 4 | +const canvas = document.querySelector("canvas"); |
| 5 | +const ctx = canvas.getContext("2d"); |
| 6 | + |
| 7 | +let blobs; |
| 8 | + |
| 9 | +const IMG_URL = "./image.avif"; |
| 10 | + |
| 11 | +const toBlob = async (type) => { |
| 12 | + return new Promise((resolve) => { |
| 13 | + canvas.toBlob((blob) => { |
| 14 | + const newImg = document.createElement("img"); |
| 15 | + const blobURL = URL.createObjectURL(blob); |
| 16 | + newImg.addEventListener("load", () => { |
| 17 | + URL.revokeObjectURL(blobURL); |
| 18 | + }); |
| 19 | + newImg.src = blobURL; |
| 20 | + document.body.append(newImg); |
| 21 | + document.body.append( |
| 22 | + document.createTextNode(`Re-encoded image as ${blob.type}`) |
| 23 | + ); |
| 24 | + resolve(blob); |
| 25 | + }, type); |
| 26 | + }); |
| 27 | +}; |
| 28 | + |
| 29 | +const img = document.createElement("img"); |
| 30 | +img.crossOrigin = "anonymous"; |
| 31 | +img.addEventListener("load", async () => { |
| 32 | + canvas.width = img.naturalWidth; |
| 33 | + canvas.height = img.naturalHeight; |
| 34 | + ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight); |
| 35 | + copyButton.style.display = "block"; |
| 36 | + blobs = await Promise.all( |
| 37 | + ["image/jpeg", "image/webp", "image/png"].map(toBlob) |
| 38 | + ); |
| 39 | +}); |
| 40 | +img.src = IMG_URL; |
| 41 | + |
| 42 | +copyButton.addEventListener("click", async () => { |
| 43 | + try { |
| 44 | + const data = {}; |
| 45 | + blobs.forEach((blob) => { |
| 46 | + data[`${blob.type !== "image/png" ? "web " : ""}${blob.type}`] = blob; |
| 47 | + }); |
| 48 | + await navigator.clipboard.write([new window.ClipboardItem(data)]); |
| 49 | + pasteButton.style.display = "block"; |
| 50 | + pasteButton.disabled = false; |
| 51 | + } catch (err) { |
| 52 | + console.error(err.name, err.message); |
| 53 | + pre.style.display = "block"; |
| 54 | + pre.textContent = `${err.name}: ${err.message}`; |
| 55 | + } |
| 56 | +}); |
| 57 | + |
| 58 | +pasteButton.addEventListener("click", async () => { |
| 59 | + const items = await navigator.clipboard.read(); |
| 60 | + for (const item of items) { |
| 61 | + console.log(item.types); |
| 62 | + for (const type of item.types) { |
| 63 | + if (!/(:?web )?image\//.test(type)) { |
| 64 | + continue; |
| 65 | + } |
| 66 | + const blob = await item.getType(type); |
| 67 | + const blobURL = URL.createObjectURL(blob); |
| 68 | + const img = document.createElement("img"); |
| 69 | + img.addEventListener("load", () => { |
| 70 | + URL.revokeObjectURL(blobURL); |
| 71 | + }); |
| 72 | + img.src = blobURL; |
| 73 | + document.body.append(img); |
| 74 | + document.body.append( |
| 75 | + document.createTextNode(`Pasted image as ${blob.type}`) |
| 76 | + ); |
| 77 | + } |
| 78 | + } |
| 79 | +}); |
0 commit comments