【无标题】

【无标题】,第1张

PC端react实现一键复制图片功能 用到的工具库

b64-to-blob、html2canvas

具体方式

过html2canvas,就可以获取完整的dom节点,再通过b64-to-blob,将base64格式转换成blob,将blob赋值到浏览器剪切板就大功告成了

复制功能代码
const copy = () => {
    html2canvas(imgRef.current, {
      useCORS: true
    }).then((canvas) => {
      const imgUrl = canvas.toDataURL('image/png');
      const str = imgUrl.replace(/data:image\/png;base64,/, '');
      const file = b64toBlob(str, 'image/png');
      const clipboardItemInput = new window.ClipboardItem({ 'image/png': file });
      window.navigator.clipboard.write([clipboardItemInput]);
    });
  };
完整代码
import React, { useState, useEffect, useRef } from 'react';
import html2canvas from 'html2canvas';
import b64toBlob from 'b64-to-blob';
import bg from 'public/1.png';


const CopyImg= (props) => {
  const imgRef= useRef();
  const copy = () => {
    html2canvas(imgRef.current, {
      useCORS: true
    }).then((canvas) => {
      const imgUrl = canvas.toDataURL('image/png');
      const str = imgUrl.replace(/data:image\/png;base64,/, '');
      const file = b64toBlob(str, 'image/png');
      const clipboardItemInput = new window.ClipboardItem({ 'image/png': file });
// 这里 window.navigator.clipboard在谷歌浏览器中,只有安全网络环境才能访问,https/localhost可以,http是访问不到的
      window.navigator.clipboard.write([clipboardItemInput]);
    });
  };
  useEffect(() => {
    init();
  }, []);
  return (
       <div>
       	  <button onClick={() => copy()}>复制图片 </button>
          <img ref={imgRef} src={bg} alt="" />
       </div>
  );
};
export default CopyImg;

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1322748.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-12
下一篇2022-06-12

发表评论

登录后才能评论

评论列表(0条)

    保存