How can I let user paste image data from the clipboard into a canvas element in Firefox in pure Javascript?

前端 未结 2 545
一向
一向 2020-12-12 11:39

I have done my best to find a simple, relevant, and up-to-date example that works for the latest version of Firefox and I\'m really struggling.

Titles says it all re

2条回答
  •  死守一世寂寞
    2020-12-12 12:04

    ViliusL's answer is great, but for those looking for a simple cross-browser way to capture a pasted image:

    window.addEventListener("paste", async function(e) {
      e.preventDefault();
      e.stopPropagation();
      let file = e.clipboardData.items[0].getAsFile();
      let objectUrl = URL.createObjectURL(file);
      // do something with url here
    });
    

    You'll probably want to do some error checking (like in ViliusL's answer), in case they paste something that's not an image. According to MDN, clipboardData works in all modern browsers. I've tested on Chrome and Firefox, and they work fine.

提交回复
热议问题