前端保存图片

import React, { useRef } from 'react';
import html2canvas from 'html2canvas';

const DownloadImage = () => {
  const elementRef = useRef(null);

  const handleDownload = () => {
    const element = elementRef.current;

    html2canvas(element).then(canvas => {
      const image = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream');
      const link = document.createElement('a');
      link.setAttribute('href', image);
      link.setAttribute('download', 'page.png');
      link.click();
    });
  };

  return (
    <div ref={elementRef}>
      {/* 这里放置你想要转换为图片的页面内容 */}
      <button onClick={handleDownload}>下载图片</button>
    </div>
  );
};

export default DownloadImage;

  

posted @ 2024-03-09 10:34  zjxgdq  阅读(13)  评论(0编辑  收藏  举报