'How to convert react component to image with html2canvas in React JS?

Hello friends I'm on an image comparator application in React JS... I try to download the image after comparison but I can't.

My App My App

My functions

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 Here is the error I get when I try to export my component to image

If anyone has a solution please don't hesitate... Thanks in advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source