DOM TO IMG

168 阅读1分钟

如果你有需求要将dom变成图片

也是在工作需求中碰到这个点进行了学习就顺便写个文章分享下,分享个使用 html2canvas 库和 React 函数组件实现 DOM 转换为图像的示例,希望对你有用。

安装依赖

npm install html2canvas --save

实现代码(实现下载)

import React, {useRef} from 'react';
import html2canvas from 'html2canvas';
import './index.scss'

const DomToImage = () => {
  const captureRef = useRef(null);

  const handleCapture = () => {
    if (captureRef.current) {
      html2canvas(captureRef.current, { useCORS: true })
        .then((canvas) => {
          const imgData = canvas.toDataURL('image/png');
          const link = document.createElement('a');
          link.href = imgData;
          link.download = 'image.png';
          link.click();
        });
    }
  }

  return (
    <div>
      <button onClick={handleCapture}>保存图片</button>
      <div ref={captureRef} className='my_element'>
        <div className='center'>center</div>
      </div>
    </div>
  );
};

export default DomToImage;

实现代码(实现数据上传)

import React, { useRef } from 'react';
import html2canvas from 'html2canvas';
import './index.scss';

const DomToImage = () => {
  const captureRef = useRef(null);

  const handleCapture = () => {
    if (captureRef.current) {
      html2canvas(captureRef.current, { useCORS: true })
        .then((canvas) => {
          canvas.toBlob((blob) => {
            // 创建表单数据对象
            const formData = new FormData();
            formData.append('image', blob, 'image.png');

            // 发送图像数据到后台服务器
            fetch('/upload', {
              method: 'POST',
              body: formData,
            })
              .then(response => {
                // 处理响应
                console.log('Image uploaded successfully!');
              })
              .catch(error => {
                // 处理错误
                console.error('Error uploading image:', error);
              });
          });
        });
    }
  };

  return (
    <div>
      <button onClick={handleCapture}>数据流上传</button>
      <div ref={captureRef} className='my_element'>
        <div className='center'>center</div>
      </div>
    </div>
  );
};

export default DomToImage;

通用css

.my_element {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 200px;
    height: 200px;
    background-color: red;
    .center {
        width: 100px;
        height: 100px;
        background-color: green;
    }
}