如何在React JS中使用html2canvas将react组件转换为图像?

问题描述 投票:0回答:1

朋友们大家好,我正在使用 React JS 中的图像比较器应用程序...我尝试在比较后下载图像,但不能。

我的应用程序 My App

我的功能

import * as html2canvas from "html2canvas";
import { saveAs as save } from "file-saver";

//Convert component to Canvas
function canvasToBlob(canvas) {
  return new Promise((resolve, reject) => {
    try {
      canvas.toBlob((blob) => {
        if (!blob) {
          return reject(new Error("Could not convert canvas to blob"));
        }
        return resolve(blob);
      });
    } catch (e) {
      return reject(e);
    }
  });
}

//Convert canvas to base64
function blobToBase64(blob) {
  return new Promise((resolve, reject) => {
    try {
      const reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onloadend = function () {
        if (typeof reader.result === "string") {
          return resolve(reader.result);
        } else {
          return reject(new Error("Could not convert blob to base64"));
        }
      };
    } catch (e) {
      return reject(e);
    }
  });
}

//Export base64 to image 
export async function exportDiv(querySelector, fileName) {
  const el = document.querySelector(querySelector);
  if (!el) {
    return "";
  }
  const canvas = await html2canvas(el, {
    backgroundColor: null,
  });
  const blob = await canvasToBlob(canvas);
  const base64 = await blobToBase64(blob);
  save(base64, fileName);
}

这是我尝试将组件导出到图像时遇到的错误 Here is the error I get when I try to export my component to image

如果有人有解决方案,请不要犹豫......提前致谢

reactjs screenshot html2canvas
1个回答
0
投票

尝试对 html2canvas 使用不同的导入并确保您使用的是版本 1.4.1:

import html2canvas from "html2canvas";
© www.soinside.com 2019 - 2024. All rights reserved.