Copy the image to the clipboard

In the previous project, I clicked a button and directly copied the two-dimensional code of the picture on the page, searched it and learnedclipboard, but can not copy the picture, can only copy the text, so can only download the TWO-DIMENSIONAL code picture down to use, now that the Web can also copy the picture.

1. Use the getSelection + execCommand API to copy the image

There’s something about Selection and execCommand, the two apis that you can read directly from this 29.7K clipboard JS library! This article.

  • html
<img id="testImg" src="./img/test.jpg" alt="img">

<button id="btn">copy</button>

Copy the code
  • js
const testImg = document.querySelector("#testImg");

const btn = document.querySelector("#btn");



function handleCopyImg({

  const selection = window.getSelection();

  // Clear the check

  if (selection.rangeCount > 0) selection.removeAllRanges();

  // https://developer.mozilla.org/zh-CN/docs/Web/API/Document/queryCommandSupported

  if(!document.queryCommandSupported('copy')) return alert('Browser does not currently support copy commands');

  // Create a range

  const range = document.createRange(); 

  range.selectNode(testImg);

  selection.addRange(range);

  document.execCommand("copy");

  selection.removeAllRanges();

}



btn.addEventListener("click", handleCopyImg, false);

Copy the code
  • Conclusion:

After the actual test, it is found that after clicking the button to copy, word document, wechat chat input box and QQ chat input box can paste the copied picture normally, but there is no reaction in the nail chat input box.

2. Navigator. Clipboard to copy pictures

  • Clipboard API compatibility, note that older browsers support, IE is not supported at all
  • html
<img id="testImg" src="./img/test.jpg" alt="img">

<button id="btn">copy</button>

Copy the code
  • js
const testImg = document.querySelector("#testImg");

const btn = document.querySelector("#btn");



function handleCopyImg({

  const canvas = document.createElement('canvas');

  const ctx = canvas.getContext('2d');

  const img = new Image();



  canvas.width = testImg.width;

  canvas.height = testImg.height;

  img.crossOrigin = "Anonymous";

  img.src = testImg.src;

  

  img.onload = (a)= > {

    ctx.clearRect(0.0, ctx.canvas.width, ctx.canvas.height);

    ctx.drawImage(img, 0.0);

    // Convert canvas to blob

    canvas.toBlob(async blob => {

      console.log(blob);

      const data = [

        new ClipboardItem({

          [blob.type]: blob,

        }),

      ];

      // https://w3c.github.io/clipboard-apis/#dom-clipboard-write

      await navigator.clipboard.write(data)

        .then(

          (a)= > {

            console.log("Copied to clipboard successfully!");

          },

() = > {

            console.error("Unable to write to clipboard.");

          }

        );

      });

  }

}



btn.addEventListener("click", handleCopyImg, false);

Copy the code
  • Conclusion:

After the actual test, in wechat, QQ, Nail chat input box can paste pictures, the only disadvantage is that the low version of the browser does not support.

3. On the clipboard

  1. The read method returns a Promise to get the copied content
async function foo({

  const items = await navigator.clipboard.read();

  const imageBlob = await items[0].getType("image/png");

  console.log("imageBlob==>", imageBlob);

}

Copy the code
  1. The readText method returns a Promise for the copied text content
async function foo({

  await navigator.clipboard.readText()

    .then(data= > {

      console.log(data);

    });

}

Copy the code
  1. The write method writes clipboard content, such as images or other files
const data = [

  new ClipboardItem({

    "text/plain"new Blob(["hello clipboard"] and {type"text/plain" }),

  }),

];

navigator.clipboard.write(data).then(

  (a)= > {

    console.log("Copied to clipboard successfully!");

  },

() = > {

    console.error("Unable to write to clipboard. :-(");

  }

);

Copy the code
  1. The writeText method writes text content
navigator.clipboard.writeText("hello!!!");

Copy the code

4. Reference materials

  1. clipboard
  2. Async Clipboard API: Asynchronous Clipboard API
  3. Clipboard API
  4. Copy images to clipboard on JavaScript web pages
  5. There’s something wrong with this 29.7K clipboard JS library!