React on a PC enables one-click image copying

Background: the front-end implementation is required to generate two-dimensional code and achieve one-click copy of pictures.

The paste effect is as follows:

React, B64-to-blob, html2Canvas

React generates the qrcode from canvas

               <div>
                <QRCode
                    value={'https://www.toutiao.com/a7003614188446761479/?log_from=105dea9e42726_1630663662691'}
                    size={200}
                    fgColor="# 000000"
                  />
                </div>
Copy the code

Then transform the whole DOM into canvas. At this time, we will find that the previous TWO-DIMENSIONAL code is already canvas and can no longer be converted with canvas, so we will modify the logic

 const [url, setUrl] = useState(' ');
  const qrCoderef = useRef();
  
 // Initialize the TWO-DIMENSIONAL code generated by canvas to the img tag through base64
  const init = () = > {
    const image = new Image();
    // Resolve canvas cross-domain issues
    image.setAttribute('crossOrigin'.'anonymous'); Image.src = 'image address';// Use image loading to trigger events
    image.onload = function () {
      try {
        const canvas = document.getElementsByTagName('canvas');
        const ctx = canvas[0].getContext('2d');
        ctx.drawImage(image, 200.200);
        const imgUrl = canvas[0].toDataURL('image/png');
        setUrl(imgUrl);
      } catch {
        message.error('Build failed, please try again'); props.onCancel(); }}; }; useEffect(() = >{ init(); } []);Copy the code
<div ref={qrCoderef}> {! url&&<QRCode
                    value={'https://www.toutiao.com/a7003614188446761479/?log_from=105dea9e42726_1630663662691'}
                    size={200}
                    fgColor="# 000000"
                  />}
                  {url && <div className={styles.imgDiv}>
                  <img className={styles.copyImg} src={url} alt="" />
                </div>}
               </div>

Copy the code

In this way, html2Canvas can be used to obtain the complete DOM node, and b64-to-blob can be used to convert base64 format to BLOB, and bloB can be assigned to the browser clipboard. Specific operation:

 const copy = () = > {
    html2canvas(qrCoderef.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]);
    });
  };

Copy the code

Complete code:

import React, { useState, useEffect, useRef } from 'react';
import { Modal, message, Popover } from 'antd';
import QRCode from 'qrcode.react';
import html2canvas from 'html2canvas';
import b64toBlob from 'b64-to-blob';
import bg from 'public/1.png';


const QrCodeModal = (props) = > {
  const [url, setUrl] = useState(' ');
  const qrCoderef = useRef();


  const copy = () = > {
    html2canvas(qrCoderef.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 });
       / / the window. The navigator. The clipboard to access in the network of security in the Google, HTTPS/localhost, HTTP is not to visit
      window.navigator.clipboard.write([clipboardItemInput]);
    });
  };
  const init = () = > {
    const image = new Image();
    image.setAttribute('crossOrigin'.'anonymous');
    image.src = bg;
    image.onload = function () {
      try {
        const canvas = document.getElementsByTagName('canvas');
        const ctx = canvas[0].getContext('2d');
        ctx.drawImage(image, 200.200);
        const imgUrl = canvas[0].toDataURL('image/png');
        setUrl(imgUrl);
      } catch {
        // The call may fail before the canvas is drawn
        message.error('Build failed, please try again'); props.onCancel(); }}; }; useEffect(() = >{ init(); } []);return (
    <Modal {. props} >
      <Popover content={<div><a onClick={()= >Copy ()}> One-click copy</a></div>} title="">
        <div ref={qrCoderef}>
          <h3 >Do you come?</h3>
          <p>
            <span>xxxx</span>
            <span>xxxxxxxxxxxxxx</span>
          </p>
          <div>{! url &&<div >
              <QRCode
                value={'https://www.toutiao.com/a7003614188446761479/?log_from=105dea9e42726_1630663662691'}
                size={200}
                fgColor="# 000000"
              />
            </div>}
            {url && <div >
              <img src={url} alt="" />
            </div>}
          </div>
        </div>
      </Popover>
    </Modal >
  );
};
export default QrCodeModal;


Copy the code