javascriptreactjshtml2canvas

HTML Element Not Picking Up By 'html2canvas' or 'dom-to-image'


I have a function that is supposed to create an HTML node element and then turn it into an image. This is a sample snippet

  async function SampleAction() {
    const html = draftToHtml(convertToRaw(description.getCurrentContent()));
    /* HTML is printing below*/
    console.log("HTML element", html);
    const invisibleDiv = document.createElement("div");
    invisibleDiv.setAttribute("id", "invisibleDiv");
    invisibleDiv.innerHTML = html;
    /* Im able to print it below */
    console.log("invisibleDiv Node element", invisibleDiv);
    /* But cannot make html2canvas*/
    const htmlDomImg = await html2canvas(invisibleDiv);
    console.log(htmlDomImg);
  }

CodeSandBox.com link to see it live: https://codesandbox.io/s/cranky-wilson-qo22cm?file=/src/App.js

My goal is to type a text, convert it to HTML, and then convert the HTML into an image. When I print out the invisibleDiv element to the console, I am able to see the HTML.

invisiblediv node element

But attempting to print it throws an error saying the element cannot be found

enter image description here


Solution

  • Marking this as answered since @Dai solved it. I just needed to actually add the element to the body using appendChild