1

我们可能在某些场景中需要复制图片 当不需要用户自己右键操作复制的时候,我们可以使用clipboard来实现(不过clipboard的兼容性不是很友好)以下为代码
HTML:
<div class="imgBox"></div>

JS

 let imgBox = document.querySelector('.imgBox');
    let img = new Image();
    img.crossOrigin = "anonymous";
    img.src = 'https://dummyimage.com/300.png'
    let canvas = document.createElement('canvas');
    img.onload = function() {
      canvas.width = img.width;
      canvas.height = img.height;
      let context = canvas.getContext('2d');
      context.drawImage(img, 0, 0);
      imgBox.appendChild(canvas)
      canvas.toBlob(function(blob) {
        if (window.ClipboardItem) {
          navigator.clipboard.write([
            new ClipboardItem({ [blob.type]: blob })
          ]);
        } else {
          //浏览器不支持
        }

      }, 'image/png');
    }

Kingsley
129 声望7 粉丝

enjoying and coding