前端指定区域一键截图下载&一键复制图片或文字到剪贴板

203 阅读1分钟

类似需求都是依赖插件html2canvas来实现,下面以两个实际需求进行举例

需求一:一键复制到系统剪贴板

<img id="code-img" :src="author" /> //图片
<button @click="copyImg">复制</button> //按钮

import author from 'assets/author.jpg'; //引入图片
import html2canvas from 'html2canvas'; //引入插件

const copyImg = () => {
  html2canvas(document.getElementById('code-img'), {
    useCORS: true, // 【重要】开启跨域配置
    allowTaint: true, // 允许跨域图片
  }).then(async (canvas) => {
    const imgUrl = canvas.toDataURL(); //拿到图片地址
    const data = await fetch(imgUrl); //根据地址发请求去拿图片数据
    const blob = await data.blob(); //把数据转换为二进制
    await navigator.clipboard.write([ //调用js写入剪贴板方法
      new ClipboardItem({
        [blob.type]: blob,
      }),
    ]);
  });
};

需求二:指定区域一键截图下载

  <div id="map"></div> //地图区域
  <button @click="screenshotAndDownloadImg">截图并下载</button> //按钮

  const screenshotAndDownloadImg = () => {
    const element = document.getElementById('map'); //拿到需要截图的区域
    let width = element.offsetWidth - 400; //自行调整截图范围
    //调整配置项
    const options = {
      useCORS: true,// 【重要】开启跨域配置
      allowTaint: true,// 允许跨域图片
      width,
      height: element.offsetHeight,
      x: 200,//调整位移
      y: 0,//调整位移
    };
    html2canvas(element, options).then((canvas) => {
      const png = canvas.toDataURL('image/png'); //拿到截图后转换为png格式图片
      const img = document.createElement('img');//创建img标签
      img.setAttribute('src', png);//添加src属性和值
      window.document.body.appendChild(img); //将img标签塞到body里面去
      download(png);//调用自行封装的下载方法下载截图
    });
  };
  
  const download = (png) => {
    var a = document.createElement('a'); //创建一个a标签
    a.href = png;//给下载的文件指定格式
    a.download = 'screenshot'; //给下载的文件取个名字
    //创建一个鼠标点击事件
    let event = document.createEvent('MouseEvents'); 
    event.initMouseEvent(
      'click',
      true,
      false,
      window,
      0,
      0,
      0,
      0,
      0,
      false,
      false,
      false,
      false,
      0,
      null
    );
    a.dispatchEvent(event); // 给a标签触发刚刚创建的点击事件执行下载
  };