乐趣区

关于es6:image图片复制

咱们可能在某些场景中须要复制图片 当不须要用户本人右键操作复制的时候,咱们能够应用 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');
    }
退出移动版