html2canvas 截图

功能

点击截图按钮,截取box元素,并展示
初始:
html2canvas 截图_第1张图片
点击截图:
html2canvas 截图_第2张图片

import html2canvas from 'html2canvas';
import { useCallback, useState } from 'react';

const Image = () => {
  const [imgSrc, setImgSrc] = useState('');

  const takeSnapshot = useCallback(async () => {
    const box = document.getElementById('box');
    if (!box) return;

    // 将html转化为canvas
    const canvas = await html2canvas(box, {
      useCORS: true,
      backgroundColor: null
    });
    console.log('canvas', canvas);

    // 将canvas中的内容转换为一个 base64 编码的字符串,用于图片展示
    const img = canvas.toDataURL('image/jpeg');
    console.log('img', img);
    setImgSrc(img);
  }, []);

  return (
    <>
      <div
        id="box"
        style={{
          height: '100px',
          width: '100px',
          border: '1px solid red',
          backgroundColor: 'white'
        }}>
        hhh
      </div>
      <button onClick={takeSnapshot}>截图</button>
      <br />
      <br />
      <br />
      <img src={imgSrc}></img>
    </>
  );
};

export default Image;

注意事项

  • 如果box元素没有设置背景颜色,默认截图的背景色会是黑色
    html2canvas 截图_第3张图片
  • 开发中一般会将由html2canvas得到的canvas,利用canvas.toBlob()方法转化为一个 Blob 对象,上传保存,从而得到图片的地址
const takeSnapshot = async (element: HTMLElement) => {
  const canvas = await html2canvas(element, {
    useCORS: true,
    backgroundColor: null,
  });
  const file = await canvasToFile(canvas);
  const snapshotUrl = await uploadImage(file);

  return snapshotUrl;
};

const canvasToFile = (canvas: HTMLCanvasElement) => {
  return new Promise<File>((resolve, reject) => {
    canvas.toBlob((blob) => {
      if (blob) {
        const file = new File([blob], 'snapshot.png');
        resolve(file);
      } else {
        reject(null);
      }
    });
  });
};

你可能感兴趣的:(前端,前端,react)